Search code examples
arraysrubystringstring-length

Array of the lengths of the strings in another array


I need to an array that lists the number of letters of each element in a different array:

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

I tried to create a variable for the length of each element. This:

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."

outputs:

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

but it seems like an inefficient way to do things. Is there a more robust way to do this?


Solution

  • Skip the word-sizes array and use 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
    

    If for some reason you still need the word-sizes array, use Array#map:

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