Wednesday, November 23, 2016

Ruby Blocks

Yield Blocks
def test_to_call_block
   puts "method"
   yield          # execute the block with yield
   puts "method"
   yield          # execute the block with yield
end
# call the method, passing it a block
test_to_call_block {puts "block"}
Running the code above results in:
C:\>ruby test_to_call_block.rb
method
block
method
block
Another Example Using Alternate Syntax
# define the method
def my_method(&block) 
  puts "in my_method"
  yield
  puts "back in my_method"
end

# call the method, passing it a block wrapped with do/end
my_method do 
  puts "Hello"
end
Running the code above results in:
C:\>ruby blocks.rb
in my_method
Hello
back in my_method
Block Parameters
def yield_with_parm(&block) 
  yield 1
  yield 2
  yield 3
end

# call the method, passing it a block
yield_with_parm do | param |
  puts param
end
Running the code above results in:
C:\>ruby yield_with_parm.rb
1
2
3
Another Example of Block Parameters
def yield_with_parm
   yield 5
   puts "You are in the method"
   yield 100
end
yield_with_parm {|i| puts "You are in the block #{i}"}
Running the code above results in:
C:\>ruby yield_with_parm.rb
You are in the block 5
You are in the method
You are in the block 100
DRY Reuse: each with yield
prices = [3.99, 4.79, 0.99]

def each
  index = 0
  while index < self.length
    yield self[index]
    index += 1
  end
end

def total(prices)
  amount = 0
  prices.each do |price|
    amount += price
  end
  amount
end

def show_discounts(prices)
  prices.each do |price|
    discount = price * 0.05
    puts format("Discount = $%.2f", discount)
  end
end

puts format("Total = $%.2f", total(prices))
show_discounts(prices)
Running the code above results in:
C:\>ruby blocks.rb
Total = $9.77
Discount = $0.20
Discount = $0.24
Discount = $0.05
Yielding with Multiple Parms
#define the method
def yielding_method 
  yield "a", "b"
end
# call yielding_method passing it a block
yielding_method {|*vals| 
  vals.each do |i|
    puts("printing #{i}")
  end
}
Running the code results in:
C:\>ruby multi_parm_yield.rb
printing a
printing b