Dear Ruby, why do you struggle to combine strings and integers?

I’m presently applying to a few different programming bootcamps. Long story short, I did programming in middle and high school, wandered away for college and my early career, and now have come back full circle, seeking out that “flow”feeling again I remember from when I used to program.

Two of them focus on Ruby, so I’m presently boning up on Ruby. It’s a very straightforward language so far. It actually reminds me a bit of C++, which I took in college, so that’s helpful too.

I also love there’s no requirement for semicolons — so many of my programs in the past have broken because of a missing semicolon somewhere.

But there’s one annoying peculiarity so far. Consider the following example:

var1 = 10
puts ‘The answer is ‘ + var1

If you did this in Javascript or PHP, no problem! But Ruby crashes, for a few reasons:

  1. Like Javascript, but unlike PHP, Ruby uses the ‘+’ operator to combine strings. PHP avoids the confusion altogether by using periods (.).
  2. Unlike Javascript, Ruby can’t decipher the intent. I don’t know why technically, I’m just beginning at this ☺.

The layman understanding I have is that Ruby isn’t sure what I want to do. Do I want to add two integers together, or combine two strings?

Due to this unfortunate design choice, in your Ruby programs you have to keep track of which variables are strings, and which are integers / float point. In fact, you may need multiple copies of one variable: the string version and the integer version.

Ugh!

Any language is going to have its quirks, and this is one of Ruby’s. Fortunately there are some short methods, “to_s” and “to_i” that can easily convert variables from one type to another.

**UPDATE** As I go through my learning, I found there is an easy way to insert variable values into a string.

var1 = 10
puts “The answer is #{var1}”

Still, as Ruby claims to be a programmer friendly language, my original point still stands ☺.

Show your support

Clapping shows how much you appreciated Charlie Benkendorf’s story.