我想弄清楚如何获取数组值的长度(索引?) 由于某种原因,它返回1,0,0,我无能为力。谁能解释一下我做错了什么? 仅供参考,这是来自RubyMonk。我试图解决它而没有得到答案..只需要一点点提升来弄清楚我做错了什么
def length_finder(input_array)
output= []
input_array.length.times do |x|
output << input_array.length[x]
end
return output
end
答案 0 :(得分:4)
不应该是:
output << input_array[x].length
您正在使用Bit reference method。
更多Ruby风格:
def length_finder(input_array)
input_array.map(&:length)
end
答案 1 :(得分:3)
这非常复杂而且不是惯用语。试试这个:
def length_finder(input_array)
input_array.map { |x| x.size }
end
那应该给你一个新的数组,每个子数组的大小作为成员。
答案 2 :(得分:0)
def length_finder(input_array)
output = []
input_array.each do |x|
output << x.length
end
return output
end
my_array = length_finder(["first", "second", "third", "forth"])