RubyGuides
Share this post!

Ruby vs Java – Strings

Let’s see how we can do some basic operations with strings with 2 languages, starting with how we declare a string variable. This is Ruby vs Java!

As you may know Java is a strong typed language, which means you need to declare the variable type, Ruby infers the type from the contents.

– Length

This one is almost identical, in fact you could use () with Ruby but it’s not required so we leave it out.

– Obtaining individual characters

You can use a Ruby string like an array, in Java you will need to use the charAt method.

– Comparing

Notice how you can’t use == for comparing strings in Java.

– Replacing

These will only replace the word ‘strings’ once, if you wanted to do it for all the repetitions of the word you need to use gsub and replaceAll.

It’s important to remember that Java strings are immutable, meaning that they can’t be modified in place, but you can assign the return value to the same variable, which internally will create a new variable and assign the new value.

On Ruby while they are mutable but you still need to assign the output of sub/gsub because these methods don’t change the string, some methods in ruby have a variant that does change the variable, these usually end with ! (an exclamation mark) like sort! and uniq! in this case we could use sub!/gsub!

And finally here are the links for the documentation for the String class for Ruby and Java:

http://ruby-doc.org/core-1.9.3/String.html

http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

1 comment
Jonny says 5 years ago

Wow I didn’t know that Ruby is a little similar to java programming, good post
Thanks 🙂

Comments are closed