hash-style parameters

T

Terry Michaels

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?
 
D

David Masover

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={}
 
P

Pablo Torres N.

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.
 
D

David Masover

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.
 
P

Pablo Torres N.

Why?

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

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
474,146
Messages
2,570,832
Members
47,374
Latest member
anuragag27

Latest Threads

Top