Ruby each 用法

用法:遍历循环

说明:

每执行一次语句块,就传递参数给 key-value 键值对。

如果 each_xxx 后不带任何参数,语句块,将返回一个 enumerator 枚举器

语法:

each do |key| ... end        # 一维数组
each do |key, value| ... end # 二维数组

each {| key, value | block }      → hsh
each_pair {| key, value | block } → hsh
each_key {| key | block }         → hsh
each_value {| value | block }     → hsh

each        → an_enumerator
each_pair   → an_enumerator
each_key    → an_enumerator
each_value  → an_enumerator

示例:

# 数组形式
j = [100, 200]
j.each do |value|
puts puts "#{value}"
end
#
# Hash形式
h = { "a" => 100, "b" => 200 }
h.each do |key, value|
puts puts "#{key} is #{value}"
end

结果:

100
200
a is 100
b is 200

示例:

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }

结果:

a is 100
b is 200

示例:

h = { "a" => 100, "b" => 200 }
h.each_key {|key| puts key }

结果:

a
b

示例:

h = { "a" => 100, "b" => 200 }
h.each {|key, value| puts "#{key} is #{value}" }

结果:

a is 100
b is 200

示例:

h = { "a" => 100, "b" => 200 }
h.each_value {|value| puts value }

结果:

100
200
赞(0) 打赏
取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

    暂无评论...