Reputation: 43
If I have an array like
names = ["John", "Sam", "Sandy", "Andrew", "Charlie"]
and I had to write a method that takes in the array as a parameter. Inside that method, iterate over the array using the each method. If the name starts with an “S”, output a message.
How would I go about doing this? So far I only have
names.each do |i|
puts i
end
Upvotes: 2
Views: 1308
Reputation: 54223
The Ruby way would be to use select
with a block or grep
with a regex first to filter the names which begin with 'S', and only then use each
to display the selected names:
names = ["John", "Sam", "Sandy", "Andrew", "Charlie"]
s_names = names.grep(/^s/i)
# or
s_names = names.select{ |name| name.downcase.start_with?('s') }
s_names.each do |name|
puts "'#{name}' starts with an 'S'"
end
# 'Sam' starts with an 'S'
# 'Sandy' starts with an 'S'
Upvotes: 0
Reputation: 5585
Ruby 1.9.2 introduced start_with?
that intakes a string as a parameter and checks its present inside another string.
In your case you could do like this.
names.each do |name|
puts 'output a message' if name.start_with?('S')
end
But for a more real life scenario you should do two things.
.strip
method for trailing spaces and then search.So you should search like this for more practical scenario.
names = ["John", "sam", " Sandy", "Andrew", "Charlie"]
names.each do |name|
puts 'output a message' if name.strip.start_with?('s', 'S')
end
Upvotes: 3
Reputation: 33420
You could try with start_with?
:
names = ["John", "Sam", "Sandy", "Andrew", "Charlie"]
names.each do |name|
puts 'output a message' if name.start_with?('S')
end
# output a message (for Sam)
# output a message (for Sandy)
Upvotes: 2