开发者

Why does ruby output values like this?

开发者 https://www.devze.com 2022-12-13 08:58 出处:网络
Fairly new to ruby, can someone开发者_StackOverflow explain why these 2 things respond differently?

Fairly new to ruby, can someone开发者_StackOverflow explain why these 2 things respond differently?

a=["A","B","C"]
puts a
A
B
C

puts "#{a}"
ABC

a.to_s returns the same output as the templating output, but shouldn't the simple "puts a" do the same?


The specified behavior of puts is that it writes stuff out with a newline afterwards. If it's an array, it writes each element with a newline.

When you do puts a.to_s, it does the to_s first (resulting in a single string) and then outputs that single string with a newline afterward.


As discussed in this thread, and for no good reason, Arrays have magically inconsistent behavior when given to puts.

array.each {|e| puts e }

is the same as:

puts array

0

精彩评论

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