当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Ruby Array class each()用法及代码示例


Array#each():each()是一种Array类方法,通过对给定块中的条件对self中的每个元素执行一次返回数组。

用法: Array.each()

参数:  block - condition to follow

返回: Each array element following the condition

代码#1:each()方法示例

# Ruby code for each() method 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
b = ["hello", "hi", "dog"] 
  
# each 
puts "each:#{a.each {|x| print x, " -- "}}\n\n"

输出:


abc -- nil -- dog -- each:["abc", "nil", "dog"]

代码2:each()方法示例

# Ruby code for each() method 
  
# declaring array 
a = ["abc", "nil", "dog"] 
  
# declaring array 
b = ["hello", "hi", "dog"] 
  
  
# each 
puts "each:#{b.each{|x| x = 2}}\n\n"
     

输出:

each:["hello", "hi", "dog"]


相关用法


注:本文由纯净天空筛选整理自mayank5326大神的英文原创作品 Ruby | Array class each() operation。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。