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?
words.map(&:length) #=> => [5, 6, 5, 6], which is shorthand forwords.map { |word| word.length }. Note String.length and String#size are used interchangeably; they are the same method.