红宝石 |枚举每个函数
Ruby 中的 Enumerator#each函数用于根据 Enumerator 的构造方式迭代对象并返回对象的值。
Syntax: A.each { |key, value| print key + ‘ = ‘ + value + “\n” }
Here, A is the initialized object.
Parameters: This function accepts constituent of the initialized object as the parameter.
Returns: the constituent elements of the initialized object.
示例 1:
# Initialising a Hash object
name_age = { 'name' => 'Geek', 'age' => '22' }
# Calling the each function
C = name_age.each { |key, value| print key + ' = ' + value + "\n" }
# Getting the key and value of hash object
puts "#{C}"
输出:
name = Geek
age = 22
{"name"=>"Geek", "age"=>"22"}
示例 2:
# Initialising a array
stooges = ['GFG', 'gfg', 'Geeks', 'Geek']
# Calling the each function
C = stooges.each { |stooge| print stooge + "\n" }
# Getting the values of the array
puts "#{C}"
输出:
GFG
gfg
Geeks
Geek
["GFG", "gfg", "Geeks", "Geek"]