user3597950 user3597950 - 1 year ago 73
Ruby Question

How to make a method take one or two arguments?

I am working on an exercise to make the following tests pass:

describe "repeat" do
it "should repeat" do
repeat("hello").should == "hello hello"

# Wait a second! How can you make the "repeat" method
# take one *or* two arguments?
# Hint: *default values*
it "should repeat a number of times" do
repeat("hello", 3).should == "hello hello hello"

I am not understanding this part for some reason.

When I use this:

def repeat(z)
return z + " " + z

The first part of the test passes but the second one fails.

Then when I try this:

def repeat(z, 2)
return z * 2

I get an error the quits the test/rake.

And then when I try:

f = 2
def repeat(z, f)
return z * f

The test won't pass and I get this message:

wrong number of arguments (1 for 2)

I have no idea what is happening here, can someone explain how this works?

Answer Source

You can define the function like following:

def repeat(z, y=2)
    return z * y

So now, repeat("hello") will result: hellohello and repeat("hello", 3) will return hellohellohello

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download