Forum: Ruby How #{} works

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
François M. (Guest)
on 2009-03-22 15:55
(Received via mailing list)
Can anyone explain this?

>> a = ["b"]
=> ["b"]
>> a == "b"
=> false
>> "#{a}" == "b"
=> true

Since a is an array, how come the last statement evaluates as true?
Sebastian H. (Guest)
on 2009-03-22 15:59
(Received via mailing list)
François Montel wrote:
> => true
>
> Since a is an array, how come the last statement evaluates as true?

"#{ ["b"] }" == ["b"].to_s #=> true
["b"].to_s == "b" #=> true
["b"].to_s #=> "b"
Leo (Guest)
on 2009-03-22 16:17
(Received via mailing list)
> >> "#{a}" == "b"
>
> => true
>
> Since a is an array, how come the last statement evaluates as true?

You could try ruby 1.9, if you prefer false:

> a = ["b"]
=> ["b"]
> "#{a}" == "b"
=> false
> "#{a}"
=> "[\"b\"]"
> ["b"].to_s
=> "[\"b\"]"
Paganoni (Guest)
on 2009-03-22 21:01
(Received via mailing list)
le 22/03/2009 14:53, François Montel nous a dit:
> Can anyone explain this?
>
>>> a = ["b"]
> => ["b"]
>>> a == "b"
> => false
>>> "#{a}" == "b"
> => true
>
> Since a is an array, how come the last statement evaluates as true?

Because, since it's embedded in a string Ruby does a .to_s against the
array. And ["b"].to_s == "b" is true
This topic is locked and can not be replied to.