JZ.
JZ.

Reputation: 21907

Iterating through an Array of Arrays returns a different value than expected

1.9.3-p286 :039 > (0...x.right.first.chem_species.size).each do |atom|
1.9.3-p286 :040 >     puts x.right.first.chem_species[atom]
1.9.3-p286 :041?>   end
H
2
O
1
 => 0...2 
1.9.3-p286 :042 > x.right.first.chem_species[0]
 => ["H", 2] 
1.9.3-p286 :043 > 

Why doesn't the puts output ["H",2] and then ["O",1]. (as the second method returns). This doesn't seem right

Upvotes: 1

Views: 67

Answers (2)

mu is too short
mu is too short

Reputation: 434945

From the fine manual:

puts(obj, ...) → nil

Equivalent to

$stdout.puts(obj, ...)

And for IO.puts:

puts(obj, ...) → nil

[...] If called with an array argument, writes each element on a new line.

So puts [1,2] prints 1 and 2 separated by newlines.

When you do this:

1.9.3-p286 :042 > x.right.first.chem_species[0]
 => ["H", 2] 

you're letting irb display the Array and irb will use inspect to produce the output and ['H', 2].inspect is ["H", 2].

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160621

It looks like:

(0...x.right.first.chem_species.size).each do |atom|
  puts x.right.first.chem_species[atom]
end

Can be more clearly written as:

x.right.first.chem_species.each do |atom|
  puts atom
end

Upvotes: 0

Related Questions