small medium large xlarge

23 Oct 2008, 15:37
Abder-Rahman Hasan Ali (5 posts)


On page (58) of this book, and in the following paragraph, what is meant by which I put parenthesis around:

The :action part is a Ruby symbol. You can think of the colon as meaning the thing named…, so :action means the thing named action. The => “goodbye” associates the string goodbye with the name action. ((((((In effect, this gives us keyword parameters for methods. Rails makes extensive use of this facility— whenever a method takes a number of parameters and some of those parameters are optional, you can use this keyword parameter facility to give those parameters values.)))))

24 Oct 2008, 14:23
Chris Bloom (4 posts)

Think of it this way. If you were writing a PHP function that accepted multiple optional arguments, it might be written as such:

@function myFunc (required_arg_1, required_arg_2, opt_arg_1 = false, opt_arg_2 = true) { … }@

Now suppose you wanted to call the function, but switch the opt_arg_2 to false. You’d still have to specify a value for opt_arg_1, even if you wanted to use the default value.

@$result = myFunc(‘foo’, ‘bar’, false, false);@

This is because you must supply the arguments for a PHP function in the order they are defined by the function declaration.

Now juxtapose that with the text from the paragraph you cited. When a Rails method accepts multiple optional parameters, you needn’t specify ALL of them - only the ones you want. You can do this because rather than specifying the arguments in a specific order, you can call them by “name”, using the :symbol => ‘value’ notation. Take the ActiveRecord find method for example. It accepts the following optional attributes:

@:conditions, :order, :group, :limit, :offset, :joins, :include, :select, :from, :readonly, :lock@

To use them, you need only specify the ones you want and omit the others. Examples (From the rdocs):

#Don't include any optional arguments

#Match based on a condition (SQL WHERE clause) and order the results
Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")

#Group the results
Person.find(:all, :group => "category")

HTH, Chris

You must be logged in to comment