當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。