2

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?

1
  • You could write words.map(&:length) #=> => [5, 6, 5, 6], which is shorthand for words.map { |word| word.length }. Note String.length and String#size are used interchangeably; they are the same method. Commented Feb 25, 2018 at 4:35

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.