简体   繁体   中英

Iterating over an array and searching the matching element with a given string in ruby

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

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.

  1. The name could also start with 's' rather than 'S' , so search for both.
  2. It could have spaces before the actual name. Use .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

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)

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM