Ruby 结构体 each()函数
each() 是Ruby中的一个内置方法,按现有顺序返回结构的每个值。如果没有传递块,它会返回一个枚举器。
语法 :struct_name.each{|x|block }
参数 :该函数接受一个单一的参数块,这是它的迭代方式。
返回值 :它按照各自的顺序返回每个结构成员。
示例 1 :
# Ruby program for each method in struct
# Include struct
Company = Struct.new(:name, :address, :zip)
#initialise struct
ele = Company.new("Geeksforgeeks", "India", 581)
# Prints the value of each member
ele.each {|x| puts(x) }
输出:
Geeksforgeeks
India
581
例2 :
# Ruby program for each method in struct
# Include struct
Employee = Struct.new(:name, :address, :zip)
#initialise struct
ele = Employee.new("Twinkle Bajaj", "India", 12345)
# Prints the value of each member
ele.each {|x| puts(x) }
输出:
Twinkle Bajaj
India
12345