Reputation: 81
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
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
Reputation: 201
You were somewhat misunderstanding the condition
(1..25).each {|n| puts n if n % 2 == 0}
Upvotes: 1
Reputation: 168239
(1..25).each{|n| puts n if n.even?}
or
puts (1..25).select(&:even?)
Upvotes: 6