另一个数组中字符串长度的数组

时间:2018-02-25 02:58:50

标签: arrays ruby string string-length

我需要一个数组,列出不同数组中每个元素的字母数:

words = ["first", "second", "third", "fourth"]

我尝试为每个元素的长度创建一个变量。这样:

first = words[0].length
second = words[1].length
third = words[2].length
fourth = words[3].length
letters = [first, second, third, fourth]
puts "#{words}"
puts "#{letters}"
puts "first has #{first} characters."
puts "second has #{second} characters."
puts "third has #{third} characters."
puts "fourth has #{fourth} characters."

输出:

["first", "second", "third", "fourth"]
[5, 6, 5, 6]
first has 5 characters.
second has 6 characters.
third has 5 characters.
fourth has 6 characters.

但这似乎是一种低效的做事方式。有没有更强大的方法来做到这一点?

2 个答案:

答案 0 :(得分:2)

跳过word-sizes数组并使用Array#each

words.each { |word| puts "#{word} has #{word.size} letters" }
#first has 5 letters
#second has 6 letters
#third has 5 letters
#fourth has 6 letters

如果由于某种原因你还需要word-sizes数组,请使用Array#map

words.map(&:size) #=> [5, 6, 5, 6]

答案 1 :(得分:0)

您可以根据需要使用每种方法,如果数组大小未知。

words = ["first", "second", "third", "fourth" , "nth"]   # => Notice the nth here
letters = []

i=0

words.each do |x|
    letters[i]=x.length
    i+=1
end

puts "#{words}"
puts "#{letters}"

i=0
words.each do |x|
    puts "#{x} has #{letters[i]} letters"
    i+=1    
end