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.
1b6ed15a6126e1d5ef4d7d15550f30bb?d=identicon&s=25 François Montel (zerohalo)
on 2009-03-22 14: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?
7a561ec0875fcbbe3066ea8fe288ec77?d=identicon&s=25 Sebastian Hungerecker (Guest)
on 2009-03-22 14: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"
87ef5d1e14b148eb596433bc17ffe690?d=identicon&s=25 Leo (Guest)
on 2009-03-22 15: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\"]"
01bb0d480d4d2777661a15165b842590?d=identicon&s=25 Paganoni (Guest)
on 2009-03-22 20: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.