tags:

views:

84

answers:

2

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?

+7  A: 

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.

deceze
that's true, even the simple case of `'a' + 1` isn't valid.
動靜能量
A: 

You can make your Ruby automatically convert to String.

class Array
  def to_string
    self.unshift("").join(" ")
  end
end

a = ["Hello", "World"]

"foo" + a.to_string

I used Ruby for a bit before Rails came out. I just downloaded it again and was playing around, then saw your question. I may be ignorant or a nutter, but hey... that's my stab at it.

NiDeep
By doing this, you added a "" element to the beginning of the array. That's a pretty jarring side effect that you should watch for. If you really want a leading space (and I argue you don't in this method) just concatenate one at the beginning.
Andy_Vulhop
Duly noted. Thank you.
NiDeep