我是Ruby的初学者,可能这个问题太容易了,但我已经花了一些时间在上面找不到解决方案。
我的Ruby脚本采用了一个数字(ex 10
)和一个名字(ex Vincent
)。我想要的是使数组看起来像
Vincent0
Vincent1..
Vincent9
我无法想出办法......
答案 0 :(得分:6)
def arrayfy(string, number)
arr = []
0.upto(number-1) do |i|
arr << "#{string}#{i}"
end
return arr
end
更新:将这些作为变量添加到班级
class Foo
def arrayfy(string, number)
0.upto(number-1) do |i|
var_string = "@#{string}#{i}"
var_symbol = var_string.to_sym
self.instance_variable_set(var_symbol, "")
end
end
end
答案 1 :(得分:3)
将Array.new
与块(docs)一起使用:
def create_array(count, name)
Array.new(10) { |i| "#{name}#{i} }
end
使用Enumerable#reduce
(docs):
def create_array(count, name)
(0...count).reduce([]) { |m,i| m << "#{name}#{i}" }
end
或使用Enumerable#each_with_object
(docs):
def create_array(count, name)
(0...count).each_with_object([]) { |i,a| a << "#{name}#{i}" }
end
使用它:
# Using the array (assigning to variables)
array = create_array(10, 'Vincent') # => ['Vincent0', 'Vincent1', 'Vincent2' ...]
name = array[1] # => 'Vincent1'
答案 2 :(得分:3)
Array.new(10) {|i| "Vincent#{i}"}
给你
["Vincent0", "Vincent1", "Vincent2", "Vincent3", "Vincent4", "Vincent5",
"Vincent6", "Vincent7", "Vincent8", "Vincent9"]
Array的文档可在http://www.ruby-doc.org/core/classes/Array.html获得(谷歌搜索阵列RDoc将为您提供URL)。
大括号中的位({|i| "Vincent#{i}"}
)称为块。你肯定想要了解它们。
答案 3 :(得分:1)
仅供记录,更具功能性的解决方案:
>> def arrayify(str, n)
.. ([str] * n).zip(0...n).map(&:join)
.. end
#=> nil
>> arrayify('Vincent', 10)
#=> ["Vincent0", "Vincent1", "Vincent2", "Vincent3", "Vincent4", "Vincent5", "Vincent6", "Vincent7", "Vincent8", "Vincent9"]
答案 4 :(得分:0)
def array_maker(number, string)
result = []
for i in 0..number do
result << "#{string}#{i}"
end
result
end