Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are these outputs different?

Tags:

ruby

These two have different output.

aArray = [[1,2],[2,3],[3,4]]

aArray.each {|subArray| puts subArray}

aArray.each {|subArray| puts "#{subArray}"}

The first each statement prints all the numbers in the array individually while the second statement prints all the subArrays.

What magic does "#" do in this case?

like image 644
ZpfSysn Avatar asked Dec 20 '25 03:12

ZpfSysn


1 Answers

The fact that the example in your question is a nested hash makes not really a difference, therefore I will simplify your question to:

Why do these two examples print different output?

puts [1,2,3]
# 1
# 2
# 3

puts "#{[1,2,3]}"
# [1, 2, 3]

From the documentation of puts:

[...] If called with an array argument, writes each element on a new line. Each given object that isn’t a string or array will be converted by calling its to_s method. [...]

That said:

puts [1,2,3]

is interpreted as:

[1,2,3].each do |element|
  puts element
end

What is basically the same as:

puts 1
puts 2
puts 3

and prints each element of the array in a line on its own.

Whereas your second example works differently:

puts "#{[1,2,3]}"

In a first step the string interpolation will happen. That means Ruby will evaluate the "#{[1,2,3]}" part. String interpolation is done by calling to_s on the expression within the #{}. Calling [1,2,3].to_s will return the string (not the array) '[1,2,3]'. This string is inserted into the outer string at the place of the interpolation. The result is one string that Ruby prints into one line in a second step. To illustrate each step:

puts "#{[1,2,3]}"
puts "#{[1,2,3].to_s}"
puts "#{'[1,2,3]'}"
puts "[1,2,3]"
# [1,2,3]
like image 136
spickermann Avatar answered Dec 24 '25 12:12

spickermann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!