Bob Cavezza's Blog

If you’re new to ruby, you’ll occasionally come across ampersands (&) and asterisks (*) in methods. I was confused by this at first. I learned what they mean after a little digging.  In the examples I use below ——> means “returns” – as in, whatever is typed in front of ——> will return what is typed to the right of ——>.

The asterisk (*) means that you can pass a variable amount of parameters to the method.


def var_args(arg1, *rest)
"Here are the parameters I defined #{arg1} and #{rest.join(', ')}"
end

var_args("one") ——> "Here are the parameters I defined one and"
var_args("one", "two") ——> "Here are the parameters I defined one and two"
var_args("one", "two", "three", "four") ——> "Here are the parameters I defined one and two and three and four"
var_args("one", "two", "three", "four","five","six","seven","eight") ——> "Here are the parameters I defined one and two and three and four and five and six and seven and eight"

In the above examples, you can see that the first variable is created as a typical variable. Any variable thereafter (due to the *rest parameter), would be put into an array called rest to be used in the method.

The ampersand (&) means that any associated block is converted to a Proc object and that object is assigned to the parameter.


def TaxCalculator
def initialize(name, &block)
@name, @block = name, block
end

def get_tax(amount)
"#@name on #{amount} = #{ @block.call(amount) }"
end
end

tc = TaxCalculator.new("Sales tax") {|amt| amt * 0.075 }
tc.get_tax 100  ——> "Sales tax on 100 = 7.5"
tc.get_tax 250  ——> "Sales tax on 250 = 18.75"

This might be a little confusing on a first look. The name parameter is taken as “Sales Tax”, but there is only 1 parameter. &block doesn’t get passed in like a typical parameter would – it gets passed in as a block. It takes the block |amt| amt * 0.075 and stores it as a Proc variable type. Here, it is stored as the instance variable, &block. At this point, you can execute the block by typing @block.call() anywhere in the class.

The examples here were taken from “Programming Ruby: The Pragmatic Programmers’ Guide Second Edition, Includes Ruby 1.8” by Dave Thomas with Chad Fowler and Andy Hunt – pages 80 and 81.

§506 · February 20, 2016 · Software Development · · [Print]

Leave a Reply