user3843070
user3843070

Reputation: 81

How do I do this simple Ruby loop?

How do I make a range from 1 through 25 and then print out only the even numbers (hint: remember modulo)? I used this as my answer:

(1..25).each {|n| print n % 2 == 0}

and got boolean values printed. I want to get the numbers instead. What do I need to change in my code above?

Upvotes: 1

Views: 73

Answers (5)

Cary Swoveland
Cary Swoveland

Reputation: 110745

Another way:

def print_even(r)
  puts ((r.first.even? ? r.first : r.first+1)..r.last).step(2) { |i| puts i }
end

print_even((1..25))
  #=> 2
  #=> 4
  #=> 6
  ...
  #=> 24
print_even((2..26))
  #=> 2
  #=> 4
  #=> 6
  ...
  #=> 26

...and another:

even = true
(1..25).each { |i| puts i if (even = !even) }

Upvotes: 0

Stoneboy
Stoneboy

Reputation: 201

You were somewhat misunderstanding the condition

(1..25).each {|n| puts n if n % 2 == 0}

Upvotes: 1

Gagan Gami
Gagan Gami

Reputation: 10251

puts (1..25).select {|n| n.even?}

Upvotes: 0

sawa
sawa

Reputation: 168239

(1..25).each{|n| puts n if n.even?}

or

puts (1..25).select(&:even?)

Upvotes: 6

Jaugar Chang
Jaugar Chang

Reputation: 3196

puts (1..25).select {|n| n % 2 == 0}

Upvotes: 1

Related Questions