Multiplying variables in Ruby? - ruby

I'm trying to create a simple pay predictor program.
I am capturing two variables, then want to multiply those variables. I have tried doing
pay = payrate * hourrate
but it seems not to work. I was told to put pay in a definition, then I tried to display the variable but it still didn't work. When I looked at the documentation, it seems that I am using the correct operator. Any guesses?
# Simple Budgeting Program
puts "What is your budget type?\nYou can say 'Monthly' 'Weekly' or 'Fortnightly'"
payperiod = gets.chomp
case payperiod
when "Monthly"
puts "You are paid monthly"
when "Weekly"
puts "You are paid weekly"
when "Fortnightly"
puts "You are paid every two weeks."
else
puts "You did not input a correct answer."
end
puts "What is your hourly rate?\n"
payrate = gets.chomp
puts "How many hours have you worked during your pay period?\n"
hourrate = gets.chomp
def pay
payrate * hourrate
end
puts "#{pay}"
preventclose = gets.chomp

The def has nothing to do with it. payrate and hourrate are strings and * means a very different thing to strings. You need to convert them to numbers first with to_i or to_f.
payrate.to_f * hourrate.to_f

You declared pay rate and hour rate as strings. In Ruby, you cannot multiply strings by other strings. However, in Ruby there are type conversions. Ruby's string class offers a method of converting strings to integers.
string = "4"
string.to_i => 4
In your case, you first need to convert BOTH strings to an integer.
def pay
payrate.to_i * hourrate.to_i
end
Here's some great information about strings.
http://www.ruby-doc.org/core-2.1.2/String.html
Hope this helps

Coercing Strings into Numbers, and Back Again
Kernel#gets generally returns a string, not an integer or floating point number. In order to perform numeric calculations, you need to coerce the string into a number first. There are a number of ways to do this, but the Kernel#Float method is often safer than String#to_i because the Kernel method will raise an exception if a string can't be coerced. For example:
print 'Pay Rate: '
rate = Float(gets.chomp)
print 'Hours Worked: '
print hours = Float(gets.chomp)
Of course, operations on floating point numbers can be inaccurate, so you might want to consider using Kernel#Rational and then converting to floating point for your output. For example, consider:
# Return a float with two decimal places as a string.
def pay rate, hours
sprintf '%.2f', Rational(rate) * Rational(hours)
end
p pay 10, 39.33
"393.30"
#=> "393.30"

Related

Ruby until always validates as false?

So I've written this piece of code to play around with numbers and the until loop:
number = rand(10)
puts number
puts "Guess the number"
guess = gets.chomp
until guess == number
puts "Guess again!"
guess = gets.chomp
end
puts "You've guessed it right! The number is #{guess}
But for some reason it it always stuck in the until loop and I am not sure why. I puts the random number to know that i guess right and try out the code. I'm completely new to Ruby, So I guess it's a very obvious thing I am missing, but I just dont see it.
From my point of view, whenever I prompt for the guess again, that guess that validated by the until loop with until guess == number.
Who can help me clear this up?
The reason is simple, and that is you're failing to cast the user input into an integer.
i.e. if I write
number = gets.chomp
and I type 1 for the number, then the number variable will equal the string "1", not the integer 1.
To fix this, just use guess = gets.chomp.to_i
Instead of guess = gets.chomp(which will return a string of the user input), use guess = gets.to_i (which will convert user input into integer)
to_i method will convert the element into integer and will drop /n character since it's not part of the integer. Don't need to add .chomp method.

Code should return highest of two numbers entered by the user

This is the code.
puts "Give me a number"
one = gets.chomp
puts "Give me another number"
two = gets.chomp
if one > two
puts "This is the bigger number #{one}"
else
puts "This is the bigger number #{two}"
end
I don't know where my fault is.
you didn't change them to integer, gets.chomp gives you string.
puts "Give me a number"
one = gets.chomp.to_i
puts "Give me another number"
two = gets.chomp.to_i
First, you are gathering input from an external user of your "application", you then have to decide how you want to manage wrong input and conversion.
In any case, gets will return a String
You are going for numbers, but are they Integer, Float ?
Since String is Comparable, your original code will run but will probably not yield the expected returns.
Let's say you are only interested in Integers.
You will have three conversion functions to consider :
Kernel#Integer (which is included in the top-level binding)
String#to_i.
String#to_i will never return an error.
'abcd'.to_i #=> 0
'1.2'.to_i #=> 1
nil.to_i #=> 0
Kernel#Integer will return an error if the String is not a valid Integer. (which I generally find more appropriate for user inputs).
Integer('0') #=> 0
Integer('abcd') #=> ArgumentError
Integer(nil) #=> TypeError
Finally, you will have to compare your inputs. I personnally would use Array#max since it conveys optimal readability (at the expense of performance still, but you do not seem to be in a performance critical system).
My final code would look like this (without error handling):
inputs = []
2.times do
puts 'Give me a number'
inputs << Integer(gets.chomp) # or use gets.chomp.to_i
end
puts "This is the bigger number : #{inputs.max}"
More refactoring can be done but I don't think it would serve for beginners in Ruby.

I keep getting this error in rubyTest.rb:11:in `+': String can't be coerced into Fixnum (TypeError) from Test.rb:11:in `<main>'

Im trying to do a project for school and i can't figure out how to fix this error. The equations I'm using look correct. I can't find the mistake. Are the equations right?
puts "Hello welcome to the bank of homeless people! How may I help you?"
puts "--type 'deposit' to deposit money to your checkings account"
puts "--type 'withdraw' to withdraw money from your checking account"
puts "--type 'display' to display your currant balance"
descion = gets.chomp.downcase
balance=0
case descion
when 'deposit'
puts "how much do you want to deposit?"
deposit = gets.chomp
balance = balance + deposit
puts "#{deposit} has been added to your checking account"
when 'withdraw'
puts "how much do you want to remove?"
withdraw = gets.chomp
balance = balance - withdraw
puts "#{withdraw} has been removed from your checking account"
when 'display'
puts "you have #{balance} in your account"
end
gets returns a string so your equations are trying to add a fixnum with a string.
Try using to_i on deposit and withdraw
A string is not a digit, therefore Ruby is attempting to find a digit but can't find it within your string.
What you need to do is convert the strings into digits..
For example:
x = "1_000"; #<= "1000" normal string
y = "1_000".to_i; #<= 1000 string converted to integer
You can also go one step further and call .to_f which will turn it into a floating point number, or a decimal.
z = "1_000.to_f; #<= 1000.0 string converted to floating point num
I'd suggest you go and look around on the web for some information on strings and how to use them, along with what you can do with them. Here's a good start: http://ruby-doc.org/core-2.0.0/String.html

I can't multiply decimals, in ruby

I'm making a interest calculator
I go 10 * .10 * 10 and i get 0 so how do i multiply a decimal without it being 0?
my source code is
def interest()
puts "Type the original loan."
loan = gets.chomp.to_i
puts "Type the amount of interest in decimal."
interest = gets.chomp.to_i
puts "How many years?"
years = gets.chomp.to_i
puts "Your interest is"
puts loan * interest * years
end
interest()
You've got integers there, so result will be an integer too. You could use 'to_f but beware, it's not good for dealing with money or anything else needing precision. Use BigDecimal instead:
require 'bigdecimal'
def interest
puts "Type the original loan."
loan = BigDecimal(gets.chomp)
puts "Type the amount of interest in decimal."
interest = BigDecimal(gets.chomp)
puts "How many years?"
years = BigDecimal(gets.chomp) # suggested in comment, agreed with that
puts "Your interest is"
puts loan * interest * years
end
What's the difference between them?
Do this
interest = gets.chomp.to_f
.to_i changes the string to an integer. An integer is a WHOLE number.
.to_f is to float, a float is a number that allows decimal places
The problem is that you're using .to_i when you don't really want to use integers here. Integers are represented without decimal parts to them, and therefore when you call .10.to_i it truncates it to 0.
Consider using floats by .to_f instead

Input string does not match a numerical range

The below ruby code is not working as expected. It doesn't seem to recognise the 1..3 range and is only reading the else condition. If I gave a number instead of a range, it works though. Not sure where I'm going wrong.
print "Enter your cost: "
cost = gets.chomp
case cost
when 1..3
puts "inexpensive"
when 3..5
puts "affordable"
else puts "no comments"
end
You're trying to match a string against an integer range. That's not going to work. Make an integer.
cost = gets.chomp.to_i
The input you get from gets is always a string, so it will never match a number range. To convert it to an integer, do this:
cost = gets.to_i
You can directly put it in case statement like so
case gets.to_i

Resources