How You Do Math with Words in Ruby - dummies

How You Do Math with Words in Ruby

By Christopher Haupt

In Ruby, you can do basic arithmetic with number data. It turns out that strings (and individual characters) have many built-in abilities, some of which look similar to symbols that look like arithmetic.

You can add two strings, and Ruby smashes the two strings together:

2.2.2 :006 > "hello" + "chris"
=> "hellochris"

Ruby isn’t smart enough to put a space between the greeting and your name, but you can do that manually:

2.2.2 :007 > "hello " + "again chris"
=> "hello again chris"

Programmers call adding two strings together concatenation (or sometimes just catenation).

If you want to display a really excited welcome, you can use multiplication, and the string will be repeated the number of times you specify, like this:

2.2.2 :014 > "hello " * 5
=> "hello hello hello hello hello "

Note that you can’t combine strings and numbers, so attempting to use the addition operator like the following leads to an error:

2.2.2 :015 > "hello number " + 5
TypeError: no implicit conversion of Fixnum into String
    from (irb):15:in `+'
    from (irb):15
    from /Users/chaupt/.rvm/rubies/ruby-2.2.2/bin/irb:11:in `<main>'

Now that you know Ruby tracks types of data, this error starts to be a little more meaningful in that it’s called a TypeError, and it can’t convert data automatically.