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
سؤال
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?
المحلول
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
نصائح أخرى
It seems you're doing the Simon Says exercise.
The purpose of this exercise is to teach you how to take one or multiple arguments, using the default values.
Whenever you assign a default value using the "x = default value", it will be used. If the method was called with a different value, it would be used.
In the example below, the default value of number is 2.
def repeat(word, number = 2)
([word] * number).join(" ")
end
Using the above, we can call repeat("Hello", 3) and it would result with "hello hello hello"
If we call repeat("Hello"), by default it will return "hello hello"
Hope this helps!!!