简体   繁体   中英

Not getting correct output from to_s

One of the examples in Peter Cooper's Beginning Ruby for polymorphism involves the to_s method. He gives this example:

puts 1000.to_s
puts [1, 2, 3].to_s
puts ({ :name => 'Fred', :age => 10 }).to_s

and shows this as the output:

1000
123
age10nameFred

but the output I get is:

1000
[1, 2, 3]
{:name=>"Fred", :age=>10}

Does anyone know why this would be the case? Was there a change in ruby, or is there something I'm doing wrong? Or not enough info to tell? How can I find it out?

The examples work using ruby 1.8.7, which is getting a bit dated. Ruby 1.9.3 (the current version) changed the to_s implementation for Arrays and Hashes.

EDIT: See Ruby 1.9 Array.to_s behaves differently?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM