Hi there:
I was learning about methods, and when I was trying to use optional
arguments I get stucked with this:
def my_method (a=‘This’, b=‘is’, c=‘great’)
puts a+’ ‘+b+’ '+c
end
If I try:
my_method(‘Ruby’)
-> Ruby is great
-> nil
But if I try:
my_method(,‘cool’)
-> SyntaxError: compile error
Any idea on how to use arguments different from the first one?.
Thank’s in advance, Ibon.
On Mon, Jun 29, 2009 at 8:20 AM, Ibon Castilla[email protected]
wrote:
my_method(‘Ruby’)
Posted via http://www.ruby-forum.com/.
Optional arguments must be passed in the order they’re declared, and
cannot be omitted. Instead, you’ll often see hashes used instead.
def my_method(options={})
o = {
:a => ‘This’,
:b => ‘is’,
:c => ‘cool’
}.merge(options)
puts “#{o[:a]} #{o[:b]} #{o[:c]}”
end
my_method( :c => ‘great’ )
Michael M. wrote:
On Mon, Jun 29, 2009 at 8:20 AM, Ibon Castilla[email protected]
wrote:
�my_method(‘Ruby’)
Posted via http://www.ruby-forum.com/.
Optional arguments must be passed in the order they’re declared, and
cannot be omitted. Instead, you’ll often see hashes used instead.
def my_method(options={})
o = {
:a => ‘This’,
:b => ‘is’,
:c => ‘cool’
}.merge(options)
puts “#{o[:a]} #{o[:b]} #{o[:c]}”
end
my_method( :c => ‘great’ )
I agree that’s probably the best approach in most cases. If you really
want ‘optional’ earlier arguments, you’d have to do something like this:
def my_method(a=nil, b=nil, c=nil)
a ||= ‘This’
b ||= ‘is’
c ||= ‘great’
puts a+’ ‘+b+’ '+c
end
p my_method(nil, nil, ‘cool’)
Hi both:
Thanks for the code. I’ll print it out to keep it safe, and not to hold
on my memory
Cheers, Ibon.