{ puts "Hello" } # 這是一個 block
do
puts "Blah" # 這也是一個 block
puts "B
end
# 處理數(shù)組 people
people = ["David", "John", "Mary"]
people.each do |person|
puts person
end
# 反復(fù)五次
5.times { puts "Ruby rocks!" }
# 從一數(shù)到九
1.upto(9) { |x| puts x }
# 迭代并造出另一個數(shù)組
a = [ "a", "b", "c", "d" ]
b = a.map {|x| x + "!" }
puts b.inspect
# 結(jié)果是 ["a!", "b!", "c!", "d!"]
# 找出符合條件的值
b = [1,2,3].find_all{ |x| x % 2 == 0 }
b.inspect
# 結(jié)果是 [2]
# 迭代并根據(jù)條件刪除
a = [ "a", "b", "c" ]
a.delete_if {|x| x >= "b" }
# 結(jié)果是 ["a"]
# 條件排序
[2,1,3].sort! { |a, b| b <=> a }
# 結(jié)果是 [3, 2, 1]
# 計算總和
(5..10).reduce {|sum, n| sum + n }
# 找出最長字串find the longest word
longest = ["cat", "sheep", "bear"].reduce do |memo,
word|
( memo.length > word.length )? memo : word
end
- 僅執(zhí)??次呼叫 pre- post- processing
file = File.new("testfile", "r")
# ...處理文件
file.close
# 但 Ruby 習(xí)慣?以下寫法
File.open("testfile", "r") do |file|
# ...處理文件
end
# 文件自動關(guān)閉
-
Yield 在方法中使用 yield 可以執(zhí)行 Code block 參數(shù)
# 定義方法
def call_block
puts "Start"
yield
yield
puts "End"
end
call_block { puts "Blocks are cool!" }
# 輸出
# "Start"
# "Blocks are cool!"
# "Blocks are cool!"
# "End"
帶有參數(shù)的Code block
def call_block
yield(1)
yield(2)
yield(3)
end
call_block { |i|
puts "#{i}: Blocks are cool!"
}
# 輸出
# "1: Blocks are cool!"
# "2: Blocks are cool!"
# "3: Blocks are cool!"
-
Proc object 可以將Code block明確轉(zhuǎn)成一個變數(shù):
def call_block(&block)
block.call(1)
block.call(2)
block.call(3)
end
call_block { |i| puts "#{i}: Blocks are cool!" }
# 輸出
# "1: Blocks are cool!"
# "2: Blocks are cool!"
# "3: Blocks are cool!"
# 或是先宣告出 proc object (有三種寫法吸奴,大同小異)
proc_1 = Proc.new { |i| puts "#{i}: Blocks are cool!" }
proc_2 = lambda { |i| puts "#{i}: Blocks are cool!" }
proc_3 = -> (i) { puts "#{i}: Blocks are cool!" }
call_block(&proc_1)
call_block(&proc_2)
call_block(&proc_3)
# 分別輸出
# "1: Blocks are cool!"
# "2: Blocks are cool!"
# "3: Blocks are cool!"