Rito
Rito

Reputation: 25

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?

Upvotes: 2

Views: 61

Answers (2)

Rishav
Rishav

Reputation: 4068

You could always use each according to your needs and if the array size is unknown.

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

Upvotes: 0

Sagar Pandya
Sagar Pandya

Reputation: 9497

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]

Upvotes: 2

Related Questions