how to use next on ruby for this case? - ruby

I'm learning Ruby On Rails program and I've came to a road block on one of the lessons. The assignment has me creating an odd numbers for the script to read starting from "20 to 0" using the next component. This is the example they've given me to change :
i = 20
loop do
i -= 1
print "#{i}"
break if i <= 0
end
This is the problem:
Add a line to your loop before your print statement. Use the next keyword so that you skip to the next iteration if the number i is odd.
How do I accomplish this?

You can just insert a next that skips the rest of the loop if the number is odd:
i = 20
loop do
i -= 1
next if i.odd?
puts "#{i}"
break if i <= 0
end

I would solve it this way:
i = 20
loop do
i -= 1
next if i%2 != 0
print "#{i}"
break if i <= 0
end

i = 20
loop do
i -= 1
next if i % 2 == 0
print "#{i}"
break if i <=1
end

Related

How can I count number of iterations/steps to find answers of a method - RUBY

How can I get the number of iterations/steps that this method takes to find an answer?
def binary_search(array, n)
min = 0
max = (array.length) - 1
while min <= max
middle = (min + max) / 2
if array[middle] == n
return middle
elsif array[middle] > n
max = middle - 1
elsif array[middle] < n
min = middle + 1
end
end
"#{n} not found in this array"
end
One option to use instead of a counter is the .with_index keyword. To use this you'll need to use loop instead of while, but it should work the same. Here's a basic example with output.
arr = [1,2,3,4,5,6,7,8]
loop.with_index do |_, index| # The underscore is to ignore the first variable as it's not used
if (arr[index] % 2).zero?
puts "even: #{arr[index]}"
else
puts "odd: #{arr[index]}"
end
break if index.eql?(arr.length - 1)
end
=>
odd: 1
even: 2
odd: 3
even: 4
odd: 5
even: 6
odd: 7
even: 8
Just count the number of iterations.
Set a variable to 0 outside the loop
Add 1 to it inside the loop
When you return the index, return the count with it (return [middle, count]).
I assume the code to count numbers of interations required by binary_search is to be used for testing or optimization. If so, the method binary_search should be modified in such a way that to produce production code it is only necessary to remove (or comment out) lines of code, as opposed to modifying statements. Here is one way that might be done.
def binary_search(array, n)
# remove from production code lines marked -> #******
_bin_srch_iters = 0 #******
begin #******
min = 0
max = (array.length) - 1
loop do
_bin_srch_iters += 1 #******
middle = (min + max) / 2
break middle if array[middle] == n
break nil if min == max
if array[middle] > n
max = middle - 1
else # array[middle] < n
min = middle + 1
end
end
ensure #******
puts "binary_search reqd #{_bin_srch_iters} interations" #******
end #******
end
x = binary_search([1,3,6,7,9,11], 3)
# binary_search reqd 3 interations
#=> 1
binary_search([1,3,6,7,9,11], 5)
# binary_search reqd 3 interations
#=> nil

Why are these loops in Ruby not outputting the same answer?

I am currently doing Project Euler problem 1. I have no idea why these two loops are not the same.
total = 0
for i in 0..1000
if (i % 3 == 0 || i % 5 == 0)
total += i
end
end
and
total = 0
(0...1000).each do |i|
total += i if (i % 3 == 0 || i % 5 == 0)
end
puts total
When you use three dots in range (0...1000), the end value is not part of the range - it is equivalent to (0..999)
So, in first case 1000 is part of the loop, but in second case it is not.

Best way to write logic for pascal triangle shape in ruby?

I want output like this
1
0 1
0 1 0
1 0 1 0
Just add print " "*(5-i) , Like this:
for i in 1..5
print " "*(5-i)
for j in 1..i
if (i%2 == 0);
k = (j%2 == 0) ? 1:0;
else;
k = (j%2 ==0) ? 0:1;
end
print k," "
end
puts
end
The n-th line is going to have n digits plus n-1 spaces - in case of the fifth line nine chars.
Generate each line as a string and print it using puts str.center(9)

'While' loop counting up

I am practicing ruby. In one of the exercises, it asks me to try and use a 'while' loop to print the numbers 1 to 50 inclusively. (counting up)
I also have a code that counts down.
i = 50
while i > 0 do
print i
i -= 1
end
anyway you could make the code above counting up?
Thanks
Try Below Simple Ruby Magics :)
(1..50).each { |n| puts n }
50.times { |n| puts n }
1.upto(50) { |n| print n }
Here counting up is being automatically inside ruby library, so dont worry about it
try
$i = 1
$num = 51
while $i < $num do
print("#$i" )
$i +=1
end
that would help..
and go to this for more help
http://www.tutorialspoint.com/ruby/ruby_loops.htm
Just to help you understand what you typed :
when you type: i -= 1, it is the same as typing: i = i - 1
when you type : i += 1, it is the same as typing : i = i + 1
You should then easily understand why, when you want to decrement your variable i, you start by initializing i at 50 (before the while loop starts).
And when you want to increment your variable i, you start by initializing i at 1 or 0.
Your are counting backwards, from i = 50 to 1. You must go from i = 1 to 50, increasing i += 1 on each loop.
Change it to this:
i = 1
while i <= 50 do
print i
i += 1
end
And a bit simplified:
(1..50).each { |number| puts number }

Loop doesn't terminate upon checking a condition

This loop does not terminate after I type x. I'm really new to Ruby, and so far, it is so much different than what I learned before - quite interesting,
total = 0
i = 0
while ((number = gets) != "x")
total += number.to_i
i += 1
end
puts "\nAverage: " + (total / i).to_s
Any help is greatly appreciated.
Because gets gives you the newline as well. You need to chomp it.
Try:
while ((number = gets.chomp) != "x")
and you'll see it starts working:
pax> ruby testprog.rb
1
5
33
x
Average: 13

Resources