So I'm using atom to code up a calculator and I can't seem to get the console to output the first instance of puts. It just says [Finished in 2.88s]. Is there anything missing that's causing my code to not be printed to the console or am I just stupid to think that it should be outputting anything to the console? Here is my code:
def add
puts "What is the first number to be added?"
n1 = gets.chomp
puts "What is the second number to be added?"
n2 = gets.chomp
answer = n1 + n2
puts "Congrats, your number is #{answer}"
end
def sub
puts "What is the first number to be subtracted?"
n1 = gets.chomp
puts "What is the second number to be subtracted?"
n2 = gets.chomp
answer = n1 - n2
puts "Congrats, your number is #{answer}"
end
def multiply
puts "What is the first number to be multiplied?"
n1 = gets.chomp
puts "What is the second number to be multiplied?"
n2 = gets.chomp
answer = n1 * n2
puts "Congrats, your number is #{answer}"
end
def divide
puts "What is the first number to be divided?"
n1 = gets.chomp
puts "What is the second number to be divided?"
n2 = gets.chomp
answer = n1 / n2
puts "Congrats, your number is #{answer}"
end
print "Would you like to add, subtract, multiply, or divide a number? "
response = gets.chomp
if response == "add" then
add
elsif response == "subtract" then
sub
elsif response == "multiply" then
multiply
else response == "divide"
divide
end
Related
I wanted to add a timer which would count the time of sorting the five highest numbers with detailing each one individually, that is, the timer starts counting when sorting starts, then saves the time of sorting the first highest number, then resets and counts the time of the second highest number until the first five numbers are counted.
Here is my code, I don't know how to place timer so it will count what I want
def bubble_sort(tablica)
n = tablica.length
liczba_max = tablica.max(5){ |a, b| a<=>b}
loop do
zamienione = false
(n-1).times do |i|
if tablica[i] > tablica[i+1]
tablica[i], tablica[i+1] = tablica[i+1], tablica[i]
zamienione = true
end
end
break if not zamienione
end
puts "Sorted array:"
tablica
end
puts "size of array:"
ilosc_liczb = gets.chomp()
i = 0
liczba = Array.new(ilosc_liczb.to_i)
puts "Unsorted array:"
while i < ilosc_liczb.to_i
nubmers = Random.new_seed
liczba[i] = nubmers
puts liczba[i]
i += 1
end
puts bubble_sort(liczba)
puts "5th number"
puts liczba[-5]
Please help me
I am new to Ruby and just read about methods and such I have been working on a program in order to get the user to type in a number and determine if it is prime or not. This is what I have so far.
print "Enter a number: "
num = gets.chomp
def prime(n)
factors = []
if num < 2
puts "#{num} is a prime number"
end
while n % num == 0 and num < n
factors.push(num)
num += 1
end
return factors
end
Not even sure if I'm on the right track. Really lost. Any help would be greatly appreciated!
require 'prime'
print "Enter a number: "
num = gets.chomp
Prime.prime?(n)
Or, from the scratch:
def prime?(n)
if n > 1
min_condition = Math.sqrt(n).to_i # The highest factor is necessary at most sqrt(n)
factors = 0
(1..min_condition).step(2).each do |i| # It's not necessary to check even numbers
factors += 1 if (n.to_f / i) % 1 == 0
break if factors > 1 # If the algorithm find 2 factors, the number isn't prime
end
!(factors > 1)
else
false
end
end
I know that you're doing this to learn Ruby, but keep in mind that you can just use Prime.prime? to determine whether or not a number is prime.
require 'prime'
Prime.prime?(3)
#=> true
Prime.prime?(4)
#=> false
As for your actual problem, you use both num and n inside your method, but num is defined outside, so won't be in scope. Also: you never seem to actually be calling prime.
There are some problems with your program:
You want to get the user to type in a number and determine if it is
prime or not but the output of your method prime doesn't answer
this question. It will return an array.
If a number is less then 2, it is not a prime number (wikipedia), so this piece of your code is wrong:
if num < 2
puts "#{num} is a prime number"
end
There are plenty of ways to check if a number is a prime number or not, this topic may help you to implement with Ruby.
If you don't want to use ruby base library than below code is useful for you
print "Enter a number: "
num = gets.chomp
def check_prime_number(num)
num = num.to_i
n = 1
factors = []
while (num >= n ) do
if (num % n == 0 )
factors << n unless factors.include?(n)
end
n += 1
end
if ( factors.size > 2)
puts "Factors of number #{num} :-> #{factors}"
elsif num > 0
puts "#{num} is prime"
end
end
check_prime_number(num)
Try if its helpful for you.
I have the code, that will generate random numbers, unless the generated random number is 0. When the result is 0, the loop breaks.
So when the loop breaks, I want a code, that keeps adding the random numbers that kept generated and display it at the last. Can I do that in ruby?
def batting
loop do
runs = [0,1,2,3,4,5,6]
myruns = runs.shuffle.first
Newscore =
puts "Press W to hit a shot"
user_input = gets.chomp
while user_input.include? "W"
puts myruns
until myruns == 0
break
Score = Score + myruns
break
This is throwing Dynamic Constant assignment error at Score = Score + myruns which I basically think, its wrong, since the myruns keep changing at every generated event?
So, I would want to create a new variable, that would store the total of all the random numbers generated until the generated random number is 0.
Could anyone help?
May be you are looking for something like this ?
def batting
runs = [0,1,2,3,4,5,6]
final_score = 0
puts "Press W to hit a shot"
user_input = gets.chomp
while user_input.include? "W"
myruns = runs.sample
if myruns != 0
final_score += myruns
else
break
end
puts "myruns=#{myruns}","final_score=#{final_score}"
puts "Press W to hit a shot"
user_input = gets.chomp
end
puts "myruns=#{myruns}","final_score=#{final_score}"
end
You can do something like this:
def batting
loop.with_object([]) do |_,obj|
x = rand 7
x == 0 ? raise(StopIteration) : obj << x
end.sum
end
batting #=> 33
batting #=> 0
batting #=> 18
Using loop this continually creates random numbers from 0 - 6 with rand 7. We use a ternary operator to stop the loop with StopIteration if x == 0, otherwise we push x into the obj array (which is initially []). Finally we sum the obj array.
Key methods: loop, Enumerable#with_object, rand, Array#sum
In the process of figuring out blocks and yields I came across these comma-separated assignments:
def fibit
n,m =1,1
loop do |variable|
yield n
n,m = m,n+m # this line
puts "n is #{n} m is #{m}"
end
end
fibit do |num|
puts "Next : #{num}"
break if num > 100
end
Why does the m get assigned first in this scenario?
Does the last one always go first? If so why?
This was also seen as only e has the value of 1 meaning e went first?
e,r=1
puts r
puts "-------"
puts e
Also, does anyone have an idea why the code-block versions just executes, where if I write the same code with no code block I actually need to call the method for it to run?
def fibit
n,m =1,1
loop do |variable|
puts "Next : #{n}"
break if n > 100
n,m = m,n+m
end
end
fibit
If I didn't have the last line it wouldn't run. Where in the first one I don't actually call the fibit method? Or is the block kicking it off?
m does not get assigned first. When using multiple assignments, all right hand side calculations are done before any assignment to the left hand side.
That's how this code works:
a = 1
b = 3
a, b = b, a
a
# => 3
b
# => 1
This would not be possible if the assignment was done serially, since you would get that both would be either equal 1 or 3.
To further prove my point, simply swap the assignment of n and m in your code, and you'll find that the result is the same:
def fibit
n,m =1,1
loop do |variable|
yield n
m,n = n+m,m # this line
puts "n is #{n} m is #{m}"
end
end
fibit do |num|
puts "Next : #{num}"
break if num > 100
end
I'm on Chapter 33 of Learn Ruby the Hard Way.
Extra credit exercise 1 asks:
Convert this while loop to a function that you can call, and replace 6
in the test (i < 6) with a variable.
The code:
i = 0
numbers = []
while i < 6
puts "At the top i is #{i}"
numbers.push(i)
i = i + 1
puts "Numbers now: #{numbers}"
puts "At the bottom i is #{i}"
end
puts "The numbers: "
for num in numbers
puts num
end
My attempt:
i = 0
numbers = []
def loops
while i < 6
puts "At the top i is #{i}"
numbers.push(i)
i = i + 1
puts "Numbers now: #{numbers}"
puts "At the bottom i is #{i}"
end
end
loops
puts "The numbers: "
for num in numbers
puts num
end
As you can see, I got as far as trying to make the block into a function, not yet making the 6 a variable.
Error:
ex33.rb:5:in `loops': undefined local variable or method `i' for main:Object (Na
meError)
from ex33.rb:15:in `<main>'
from ex33.rb:15:in `<main>'
What am I doing wrong?
EDIT: Okay, improved it a little. Now the numbers variable is out of scope...
def loops (i, second_number)
numbers = []
while i < second_number
puts "At the top i is #{i}"
i = i + 1
numbers.push(i)
puts "Numbers now: #{numbers}"
puts "At the bottom i is #{i}"
end
end
loops(0,6)
puts "The numbers: "
for num in numbers
puts num
end
As #steenslag says, i is out of scope within loops. I would not recommend switching to using #i because i is only used by loops.
Your function is a utility that can be used to produce an array of numbers. The function uses i to figure out how far through it is (but the caller of the function doesn't care about this, it only wants the resulting numbers). The function also needs to return numbers, so move that inside loops too.
def loops
i = 0
numbers = []
while i < 6
puts "At the top i is #{i}"
numbers.push(i)
i = i + 1
puts "Numbers now: #{numbers}"
puts "At the bottom i is #{i}"
end
end
You now have to think about the fact that the caller of loops can no longer see numbers. Good luck with your learning.
When you say def, i goes out of scope. The method can't "see" it. Use #i in stead (the # gives the variable a greater "visibility"), or move the i=6 inside the method, or figure out how to use parameters with a method.
I may have misread the 'convert the while loop' but my solution was:
def loop(x, y)
i = 0
numbers = []
while i < y
puts "At the top i is #{i}"
numbers.push(i)
i += 1
puts "Numbers now: ", numbers
puts "At the bottom i is #{i}"
end
puts "The numbers: "
# remember you can write this 2 other ways?
numbers.each {|num| puts num }
end
loop(1, 6)