2013-02-17 226 views
1
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 > 

不同的价值,为什么不卖出期权输出 ["H",2]然后["O",1]。 (作为第二种方法返回)。这似乎并不正确通过数组的数组迭代返回比预期

+0

什么是'chem_species'类 - 它是一个哈希? – PinnyM 2013-02-17 04:35:39

+0

x.right.first.chem_species.class - > Array – 2013-02-17 04:43:37

回答

2

fine manual

看跌期权(OBJ,...)→零

相当于

$stdout.puts(obj, ...) 

而对于IO.puts

放(OBJ,...)→零

[...]如果与数组参数调用时,在新的一行写入每个元素。

所以puts [1,2]打印12通过换行分隔。

当你这样做:

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

你让irb显示阵列和irb将使用inspect生产输出和['H', 2].inspect["H", 2]

0

它看起来像:

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

可以更清楚地写为:

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

简而言之:'x.right.first.chem_species.each&method(:puts)':-) – mudasobwa 2013-02-17 08:52:43