Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Ruby Programming
Previous Page Home Next Page

Methods and Blocks

As we discussed in the section on blocks and iterators beginning on page 38, when a method is called, it may be associated with a block. Normally, you simply call the block from within the method using yield.

def takeBlock(p1)
  if block_given?

takeBlock("no block") "no block"
takeBlock("no block") { |s| s.sub(/no /, '') } "block"

However, if the last parameter in a method definition is prefixed with an ampersand, any associated block is converted to a Proc object, and that object is assigned to the parameter.

class TaxCalculator
  def initialize(name, &block)
    @name, @block = name, block
  def getTax(amount)
    "#@name on #{amount} = #{ }"
tc ="Sales tax") { |amt| amt * 0.075 }
tc.getTax(100) "Sales tax on 100 = 7.5"
tc.getTax(250) "Sales tax on 250 = 18.75"

Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire