Methods optional arguments

I

Ibon Castilla

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

Michael Morin

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=3D'This', b=3D'is', c=3D'great')
=A0puts a+' '+b+' '+c
end

If I try:
=A0my_method('Ruby')
=A0-> Ruby is great
=A0-> nil

But if I try:
=A0my_method(,,'cool')
=A0-> SyntaxError: compile error

Any idea on how to use arguments different from the first one?.

Thank's in advance, Ibon.

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=3D{})
o =3D {
:a =3D> 'This',
:b =3D> 'is',
:c =3D> 'cool'
}.merge(options)

puts "#{o[:a]} #{o[:b]} #{o[:c]}"
end

my_method( :c =3D> 'great' )
 
B

Brian Candler

Michael said:
�my_method('Ruby')

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')
 
I

Ibon Castilla

Hi both:

Thanks for the code. I'll print it out to keep it safe, and not to hold
on my memory ;)

Cheers, Ibon.
 

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

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top