A
A
arruah2019-01-16 20:50:53
ruby
arruah, 2019-01-16 20:50:53

How to avoid repeat in ruby ​​loop?

I'm learning ruby. There is a task where you need to find common elements in two arrays and display them on the screen.
The requirement to use the iterator each.
In this example, the result of the work should be like this:
3, 4, 5 As an artist
, I see it like this:

first_array = [1, 2, 3, 4, 5]
second_array = [3, 4, 5, 6, 7, 8]

result = first_array & second_array
result.each do |x| 
  if x != result.last
  comma = ", " 
  print x.to_s + comma
  else 
    comma = ""
  print x.to_s + comma
  end
  end

Obviously, here it is possible and necessary to avoid the reuse of print

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2019-01-16
@arruah

puts (first_array & second_array).map(&:to_s).join(', ')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question