ConnerAiken
ConnerAiken

Reputation: 194

Multiplying variables in 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

Upvotes: 0

Views: 15322

Answers (3)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84353

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"

Upvotes: 0

user3760731
user3760731

Reputation:

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

Upvotes: 0

Max
Max

Reputation: 22325

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

Upvotes: 3

Related Questions