如何在Ruby中重复一次或多次字符串
如何在Ruby中重复字符串一次或多次如何在Ruby中重复一次或多次字符串,ruby,Ruby,如何在Ruby中重复字符串一次或多次 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 "
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
如果缺少参数[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)>'
在这里,如果args[1]==nil,则验证ARGV中的第二个值是否为nil并将其设置为1,但在while语句中,您使用的是second_arg,它已获取args[1]的值,因此,很可能无法通过您的验证:
if args[1] == nil
args[1] = 1
end
您可以尝试在该验证中设置第二个_arg变量,而不是设置args[1]:
Ruby中的任何语句都会返回最后一个计算表达式的值,因此您可以将str作为repeat方法中的最后一个值,并将其作为返回值进行计算。在设置second_arg之前,必须先设置args[1]
也可以改用条件赋值运算符:
# The two lines do the same thing
args[1] = 1 if args[1] == nil
args[1] ||= 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
def repeatstr怎么了,count=2 str*count end?@JörgWMittag你赢了我。另请注意,现在的情况是,默认参数[1]到1重复,没有计数,不会重复,因为1-1=0,因此while循环将结束。这里绝对没有理由使用可变长度参数列表。更慢,更多的代码,更不清晰。不确定是谁否决了这一点,但这正是我想到的第一件事。不是否决者,但可能是因为代码中缺少Ruby的冗长。你可以在一行方法定义中看到不必要的返回、for循环、+=、连接的+等等@SebastianPalma你注意到代码上方的内容了吗?或者,如果您希望手动循环它:。该代码演示了join的功能。
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
"hello" * 5 # => "hellohellohellohellohello"
Array.new(5, "hello").join(" ") # => "hello hello hello hello hello"