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!

Ruby: my_string = "Playing with strings"
Java: String my_string = "Playing with strings"

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

Ruby: my_string.length
Java: my_string.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

Ruby: my_string[2]
Java: my_string.charAt(2)

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

– Comparing

Ruby: my_string == other_string
Java: my_string.equals(other_string)

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

– Replacing

Ruby: my_string.sub('strings','Ruby')
Java: my_string.replace('strings','Java')

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:

1 comment
Jonny says 6 years ago

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

Comments are closed