user3597950 user3597950 - 21 days ago 7
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"
end

# 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"
end
end


I am not understanding this part for some reason.

When I use this:

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


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

Then when I try this:

def repeat(z, 2)
return z * 2
end


I get an error the quits the test/rake.

And then when I try:

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


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

You can define the function like following:

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

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