Hash-style parameters

Some function calls I’ve seen, like in Shoes, look like so:

para “Paragraph Text”, :style => “this”, :whatever => “that”

How do I define a function call so that can take one “normal” parameter
and then an unknown number of key/value pairs?

On Saturday, August 14, 2010 01:23:21 pm Terry M. wrote:

Some function calls I’ve seen, like in Shoes, look like so:

para “Paragraph Text”, :style => “this”, :whatever => “that”

How do I define a function call so that can take one “normal” parameter
and then an unknown number of key/value pairs?

You could answer your own question by looking at the source of the
program
doing this – and I’d suggest it for anything you want to learn more
about.

For this case, remember that this basically becomes:

para(“Paragraph Text”, {:style => “this”, :whatever => “that”})

And of course, there’s no reason those literals need to be there – you
could
just do this:

text = “Paragraph Text”
hash = {:style => “this”, :whatever => “that”}
para(text, hash)

So, it should be clear that this is what you want:

def para text, options

There is one catch, though – you said “unknown number”, which could be
zero,
so you need a default value:

def para text, options={}

On Sat, Aug 14, 2010 at 13:58, David M. [email protected] wrote:

So, it should be clear that this is what you want:

def para text, options

There is one catch, though – you said “unknown number”, which could be zero,
so you need a default value:

def para text, options={}

Just a note: while you can omit parens in method definitions, most
code does only if the method takes no arguments, if it does, leave the
parens there.

On Saturday, August 14, 2010 05:50:22 pm Pablo Torres N. wrote:

Just a note: while you can omit parens in method definitions, most
code does only if the method takes no arguments, if it does, leave the
parens there.

Why?

I find it more readable without parens, but with syntax highlighting,
mostly
because that’s how I call methods.

def para text, options

There is one catch, though – you said “unknown number”, which could be
zero,
so you need a default value:

def para text, options={}

There is also the “named parameter” gem which might be useful to you:
http://github.com/rdp/arguments

On Sun, Aug 15, 2010 at 00:56, David M. [email protected] wrote:

Just a convention, I guess precisely so you can easily tell method
definitions and method invocations apart. Consider:

def say_hi(tittle, name)
puts “Hi, #{tittle} #{name}”
end

tittle = “Dr.”
name = “Cham”

some_obj.instance_eval do
def say_hi tittle, name
puts “Howdy, #{tittle} #{name}”
end
end

A bit ambiguous.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs