1
我想創造一個字符串的前三個字符重複的給定次數這樣的節目串:紅寶石文本
foo('Chocolate', 3) # => 'ChoChoCho'
foo('Abc', 3) # => 'AbcAbcAbc'
我知道我可以使用length
來算字符,但我如何指定要輸出的字符串的長度?另外我怎樣才能指定次數?
我想創造一個字符串的前三個字符重複的給定次數這樣的節目串:紅寶石文本
foo('Chocolate', 3) # => 'ChoChoCho'
foo('Abc', 3) # => 'AbcAbcAbc'
我知道我可以使用length
來算字符,但我如何指定要輸出的字符串的長度?另外我怎樣才能指定次數?
你可以使用這樣的東西。
def print_first_three_x_times(string, x)
#remove everything but the first three chars
string.slice!(3..string.length)
#print x times
x.times{ print string }
end
輸出:
[email protected] ~
$ irb
irb(main):008:0> print_first_three_x_times("Hunter",5)
HunHunHunHunHun=> 5
irb(main):009:0>
def foo(str, n)
str[0..2] * n
end
+1,您的解決方案是更好的方式。 – 2012-02-29 04:14:53