⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 01 - writing a method that accepts a block.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
def call_twice  puts "I'm about to call your block."  yield  puts "I'm about to call your block again."  yieldendcall_twice { puts "Hi, I'm a talking code block." }# I'm about to call your block.# Hi, I'm a talking code block.# I'm about to call your block again.# Hi, I'm a talking code block.#---def repeat(n) if block_given?    n.times { yield }  else    raise ArgumentError.new("I can't repeat a block you don't give me!")  endendrepeat(4) { puts "Hello." }# Hello.# Hello.# Hello.# Hello.repeat(4)# ArgumentError: I can't repeat a block you don't give me!#---puts("Print this message.") { puts "And also run this code block!" }# Print this message.#---def call_twice  puts "Calling your block."  ret1 = yield("very first")  puts "The value of your block: #{ret1}"  puts "Calling your block again."  ret2 = yield("second")  puts "The value of your block: #{ret2}"endcall_twice do |which_time|  puts "I'm a code block, called for the #{which_time} time."  which_time == "very first" ? 1 : 2end# Calling your block.# I'm a code block, called for the very first time.# The value of your block: 1# Calling your block again.# I'm a code block, called for the second time.# The value of your block: 2#---squares = {0=>0, 1=>1, 2=>4, 3=>9}squares.find { |key, value| key > 1 }          # => [2, 4]#---class Hash  def find_all    new_hash = Hash.new    each { |k,v| new_hash[k] = v if yield(k, v) }    new_hash  endendsquares.find_all { |key, value| key > 1 }        # => {2=>4, 3=>9}#---squares.dup.delete_if { |key, value| key > 1 }   # => {0=>0, 1=>1}squares.dup.delete_if { |key, value| key <= 1 }  # => {2=>4, 3=>9} #---[1, 2, 3].each# LocalJumpError: no block given#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -