【问题标题】:Modifying array of hashes inside an iterator only modifies the last item修改迭代器内的哈希数组仅修改最后一项
【发布时间】:2016-05-19 19:58:32
【问题描述】:

我有一个散列数组,我不想修改每个散列。所以我正在迭代我的源数据——在这个例子中只是迭代数字并修改每个哈希值。 但是在迭代器的上下文之外,只修改了数组的一个元素而不是所有元素,并且数组的第一个元素被最后一个元素覆盖。

arr = [{ id: 1 }, { id: 2 }, { id: 3 }]

1.upto(3) do |i|
  a = arr.detect { |t| t[:id] = i }
  a[:content] = 'this is my content'
end

puts arr

输出

{:id=>3, :content=>"this is my content"}
{:id=>2}
{:id=>3}

预期输出

{:id=>1, :content=>"this is my content"}
{:id=>2, :content=>"this is my content"}
{:id=>3, :content=>"this is my content"}

【问题讨论】:

标签: arrays ruby hash


【解决方案1】:

使用mapeach

arr = [{ id: 1 }, { id: 2 }, { id: 3 }]
arr.map { |e| e.merge(content: 'this is my content')}
=> [{:id=>1, :content=>"this is my content"}, 
    {:id=>2, :content=>"this is my content"}, 
    {:id=>3, :content=>"this is my content"}]

或者您可以在代码中将== 替换为=

a = arr.detect { |t| t[:id] == i }

== - 相等,= - 赋值

【讨论】:

  • @PascalTurbo 在我的回答中我说有问题。你使用赋值而不是相等。
【解决方案2】:

如果你想修改arr的元素,你可以写:

arr = [{ id: 1 }, { id: 2 }, { id: 3 }]

arr.map { |h| h.tap { |g| g[:content] = "this is my content" } }
  # => [{:id=>1, :content=>"this is my content"},
  #     {:id=>2, :content=>"this is my content"},
  #     {:id=>3, :content=>"this is my content"}] 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 2016-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多