Search code examples
rubycoercion

Why does Ruby need to force an Array into string by using "to_a" if it is clear it is a String addition?


For example:

ruby-1.9.2-p0 > a = ['hello', 'world']
 => ["hello", "world"] 

ruby-1.9.2-p0 > "foo" + a
TypeError: can't convert Array into String
    from (irb):3:in `+'
    from (irb):3
    from /Users/peter/.rvm/rubies/ruby-1.9.2-p0/bin/irb:17:in `<main>'

ruby-1.9.2-p0 > "foo" + a.to_s
 => "foo[\"hello\", \"world\"]" 

ruby-1.9.2-p0 > puts "foo" + a.to_s
foo["hello", "world"]

why can't Ruby automatically convert the array to String?


Solution

  • It's not that Ruby can't, it's more that it won't. It's a strongly typed language, which means you need to take care of type conversions yourself. This is helpful in catching errors early that result from mixing incompatible types, but requires a little more care and typing from the programmer.