📜  红宝石 |枚举器 each_with_object函数

📅  最后修改于: 2022-05-13 01:55:31.896000             🧑  作者: Mango

红宝石 |枚举器 each_with_object函数

Ruby 中的 each_with_object函数用于迭代给定对象的每个元素。

示例 1:

# Calling the .each_with_object function on an array object
[:gfg, :geeks, :geek].each_with_object({}) do |item, hash|
  
# Converting the array elements into its uppercase
  hash[item] = item.to_s.upcase
end

输出:

{:gfg=>"GFG", :geeks=>"GEEKS", :geek=>"GEEK"}

示例 2:

# Calling the .each_with_object function on a hash
{ foo: 2, bar: 4, jazz: 6 }.each_with_object({}) do 
|(key, value), hash|
  
# Getting the square of the hash's value
  hash[key] = value**2
end

输出:

{:foo=>4, :bar=>16, :jazz=>36}