开发者

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>'
开发者_StackOverflow
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?


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.


Strings are a special case because you can use string interpolation to call to_s implicitly:

obj = Object.new.tap {|o|
  def o.to_s
    'object!'
  end
  def o.inspect
    '[object]'
  end
}

"foo: " + obj  # TypeError
"foo: #{obj}"
=> "foo: object!"

I redefined inspect to show that to_s is being called, and not inspect. On ruby 1.9, Object#inspect calls to_s, so if I didn't redefine inspect, the above code wouldn't show clearly which method was actually being called during interpolation.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜