如何使用 case 语句遍历对象数组并将值添加到数组内的键?

How do I use a case statement to loop through an array of objects and add a value to a key inside the array?

我想使用 case 语句查看一组对象,并向键名添加一个新值。我是编程新手,请使用最简单的示例和解释。

我尝试编写一个 case 语句,使用等号运算符将新值添加到键名。

beatles = [
    {
      name: nil,
      nickname: "The Smart One"
    },
    {
      name: nil,
      nickname: "The Funny One"
    },
    {
      name: nil,
      nickname: "The Cute One"
      },
    {
      name: nil,
      nickname: "The Quiet One"
    }
  ]

  i = 0
  while i < beatles.length
    case beatles
    when nickname == "The Smart One"
        name = "John"
    when nickname == "The Funny One"
        name = "Ringo"
    when nickname == "The Cute One"
        name = "Paul"
    when nickname == "The Quiet One"
        name = "George"
    end
    i += 1
  end

  i = 0
  while i < beatles.length
    puts "Hi, I'm #{beatles[i][:name]}.  I'm #{beatles[i][:nickname]}!"
    i += 1
  end

没有人在 Ruby 中使用 while 循环(我们使用 Enumerable#eachEnumerable#mapEnumerable#reduce,)但是为了回答此处陈述的问题是请求的版本。

while i < beatles.length
  beatles[i][:name] =
    case beatles[i][:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
  i += 1
end

case 将其参数与变体进行比较(使用 Object#=== 方法。)此外,您不想分配 name inside case,不如赋值给case的结果。


Ruby 惯用版本:

beatles.each do |beatle|
  beatle[:name] =
    case beatle[:nickname]
    when "The Smart One" then "John"
    when "The Funny One" then "Ringo"
    when "The Cute One" then "Paul"
    when "The Quiet One" then "George"
    end
end