0
test = 
 {:content=>"type_name", :content_length=>9, :array_index=>0},
 {:content=>"product_id", :content_length=>10, :array_index=>1},
 {:content=>"First Item", :content_length=>10, :array_index=>0},
 {:content=>"1111", :content_length=>4, :array_index=>1}

pp  test.map {|x| puts x} #=> 
{:content=>"type_name", :content_length=>9, :array_index=>0}
{:content=>"product_id", :content_length=>10, :array_index=>1}
{:content=>"First Item", :content_length=>10, :array_index=>0}
{:content=>"1111", :content_length=>4, :array_index=>1}
[nil, nil, nil, nil]

那一系列 nil 的原因是什么?该地图完美运行,但随后导致这些零点!

4

2 回答 2

0

问题在于 #map 旨在将数组转换为不同的数组。一般情况下,#map 的块不会有副作用。下面是使用 #map 将数组中的所有数字加倍:

[1, 2, 3].map { |n| n * 2}    # => [2, 4, 6]

如果您的循环的目的仅仅是为了产生副作用(例如打印元素),您需要 #each 代替:

[1, 2, 3].each { |n| puts n }
# => 1
# => 2
# => 3

在这种情况下,我们不关心#each 的返回值。我们关心的是每个数字都会被打印出来。

于 2014-02-11T17:53:40.517 回答
-1

啊,多么愚蠢的错误!这修复了它:

test.map {|x| puts x}

我很漂亮地打印了 puts 语句,而 irb 试图提供帮助,四次返回 nil!

于 2013-10-08T19:14:14.913 回答