This might be a stupid question, but I am attempting to learn the basic's of Ruby so please be gentle. I would like to iterate thru an array of strings and then thru each letter in that string.
groceries = ['turkey', 'cranberries', 'stuffing', 'pumkin pie', 'whip-cream']
for i in groceries do
p i
for x in i do
p x
end
end
When I attempt to run this I get the following error. Any assistance would be awesome.
undefined method `each' for "turkey":String (NoMethodError)
CodePudding user response:
As mu is too short said each
seems to be more aligned with standard Ruby convention. That said, I'm a novice with Ruby and programming in general. So take my opinions with a grain of salt.
At any rate, there are a few useful methods that seem to fit your need. each_char
and chars
will iterate through a string.
for i in groceries do
p i
i.chars { |c| p c }
end
Or,
groceries.each do |i|
p i
i.chars { |c| p c }
end
CodePudding user response:
Using Array#map and String#each_char
For-loops are syntactic sugar in Ruby, and you generally won't see them in idiomatic Ruby code. Instead, Rubyists tend to use iterator methods. The following is more idiomatic, although there are certainly other ways to do what you are looking to accomplish.
groceries.map { |item| p item; item.each_char { |char| p char } }
In addition to printing the output you wanted, this has the benefit of returning your original Array of String values as well:
#=> ["turkey", "cranberries", "stuffing", "pumkin pie", "whip-cream"]
This works on any version of Ruby >= 2.7.1 (possibly earlier, but I didn't bother to test). You may be able to take further shortcuts using features from later Ruby versions, but this should certainly get you started.