Ruby Retrieve mails with number of pairs without too much code modification

Viewed 25
email = []
start = 1
while start < 51
  email.push ("jean.dupont.#{start}@email.fr")
  start += 1
end
puts email

When I do puts email I want to retrieve all the mails which only have even numbers.

I have looked a lot on google or stackoverflow and see that most are tweaking their code but I would like not to touch mine too much, although I know it's necessary.

What is the correct method to retrieve peer emails with this code?

2 Answers

you can use a select on the email array and extract the number by using [/\d+/] and check if it's even directly in the puts then filter by that condition

puts email.select { |e| e[/\d+/].to_i.even? }

[/\d+/] being the equivalent of scan(/\d+/)[0]

The minimum change you can do is to add an if condition to only push elements when start is even (start.even?):

email.push("jean.dupont.#{start}@email.fr") if start.even?

But, being Ruby I think there are a couple of methods you can use to get something similar done:

(1..50)                                            # create a range of numbers from 1 to 50
  .select(&:even?)                                 # select from the range only those elements that are even
  .map { |start| "jean.dupont.#{start}@email.fr" } # map each element to create a string using their values
  .each(&method(:puts))                            # iterate over each element and invoke `puts` using the element as the argument

A good exercise would be to rethink your code to give you the same output, but doing the less possible. For instance, the loop, if you don't need the odd elements, it's worthless working with them. You can make the elements in your iteration be only those that you need.

As well as the email accumulator you declare at the beginning. Most of the time you can achieve that by mapping your object (being a Hash or Array instance or any that responds to map).

Related