code block 发表于 2017-11-15 | code block ⼀种匿名⽅法 123456{ puts "Hello" } # 这是一個 blockdo puts "Blah" # 这也是一個 block puts "Bend 內部迭代器(iterator) 123456789# 处理数组 peoplepeople = ["David", "John", "Mary"]people.each do |person| puts personend# 反复五次5.times { puts "Ruby rocks!" }# 从一数到九1.upto(9) { |x| puts x } 其他迭代⽅式 123456789# 迭代并造出另一个数组a = [ "a", "b", "c", "d" ]b = a.map {|x| x + "!" }puts b.inspect# 结果是 ["a!", "b!", "c!", "d!"]# 找出符合条件的值b = [1,2,3].find_all{ |x| x % 2 == 0 }b.inspect# 结果是 [2] 当作判断条件 1234567# 迭代并根据条件刪除a = [ "a", "b", "c" ]a.delete_if {|x| x >= "b" }# 结果是 ["a"]# 条件排序[2,1,3].sort! { |a, b| b <=> a }# 结果是 [3, 2, 1] functional programming 1234567# 计算总和(5..10).reduce {|sum, n| sum + n }# 找出最长字串find the longest wordlongest = ["cat", "sheep", "bear"].reduce do |memo,word| ( memo.length > word.length )? memo : wordend 仅执⾏⼀次呼叫 pre- post- processing 12345678file = File.new("testfile", "r")# ...处理文件file.close# 但 Ruby 习惯⽤以下写法File.open("testfile", "r") do |file| # ...处理文件end# 文件自动关闭 Yield 在方法中使用 yield 可以执行 Code block 参数 1234567891011121314151617181920212223242526272829# 定义方法def call_block puts "Start" yield yield puts "End"endcall_block { puts "Blocks are cool!" }# 输出# "Start"# "Blocks are cool!"# "Blocks are cool!"# "End"带有参数的Code blockdef call_block yield(1) yield(2) yield(3)endcall_block { |i| puts "#{i}: Blocks are cool!"}# 輸出# "1: Blocks are cool!"# "2: Blocks are cool!"# "3: Blocks are cool!" Proc object 可以将Code block明确转成一个变数: 1234567891011121314151617181920212223242526def call_block(&block) block.call(1) block.call(2) block.call(3)endcall_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!"