如何在Ruby中重复一次或多次String?
def repeat(*args)
str, second_arg, count = "", args[1], 1
if args[1] == nil
args[1] = 1
end
while second_arg >= count
str += args[0] + " "
second_arg -= 1
end
return str
end
我概述的测试是:
describe "repeat" do
it "should repeat" do
expect(repeat("hello")).to eq("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
expect(repeat("hello", 3)).to eq("hello hello hello")
end
end
如果缺少argument[1]
,我想用值“1”填充它,这样它至少会返回1.
这是我的错误:
Failures:
1) Simon says repeat should repeat
Failure/Error: expect(repeat("hello")).to eq("hello hello")
NoMethodError:
undefined method `>=' for nil:NilClass
# ./lib/03_simon_says.rb:14:in `repeat'
# ./spec/03_simon_says_spec.rb:39:in `block (3 levels) in <top (required)>'
答案 0 :(得分:3)
此处if args[1] == nil
您要验证ARGV
中的第二个值是nil
并将其设置为1
,然后在while
语句中您使用的second_arg
已经使用args[1]
的值,因此,很可能它不会通过您的验证:
if args[1] == nil
args[1] = 1
end
您可以尝试在该验证中设置second_arg
变量,而不是设置args[1]
:
if args[1] == nil
second_arg = 1
end
此外,“ Ruby中的任何语句都会返回上次评估的表达式的值”,因此您只需将str
作为repeat
方法中的最后一个值即可将被评估为返回值。
答案 1 :(得分:1)
在设置args[1]
之前,您必须设置second_arg
。
def repeat(*args)
args[1] = 1 if args[1] == nil
str, second_arg, count = "", args[1], 1
while second_arg >= count
str += args[0] + " "
second_arg -= 1
end
return str
end
您也可以使用条件赋值运算符:
# The two lines do the same thing
args[1] = 1 if args[1] == nil
args[1] ||= 1
答案 2 :(得分:1)
你完全过于复杂了。这里绝对没有理由使用可变长度参数列表。它更慢,代码更多,而且不太清楚。测试代码自己说:“提示:*默认值*”
def repeat(str, count = 2)
return Array.new(count, str).join(" ")
end
或者如果您更喜欢手动循环它:
def repeat(str, count = 2)
result = str
for _ in 0...count-1
result += " " + str
end
return result
end
答案 3 :(得分:0)
"hello" * 5 # => "hellohellohellohellohello"
Array.new(5, "hello").join(" ") # => "hello hello hello hello hello"