Celsius to Fahrenheit conversion? - ruby

I wrote the following code in Ruby for Celsius to Fahrenheit conversion. I keep getting error. I am sure that I am still not clear on the concept of methods and that's why I cant figure it out.
puts "Enter the Degree in c:"
c = gets.chomp
def celsius_fahrenheit (f)
return f = ( c * 9 / 5) + 32
end
answer = "The #{celsius_fahrenheit (f)} equivalent is"
puts answer

You have several problems:
convert c to Float
change signature of celsius_fahrenheit to use c as a parameter
don't do an assignment in the method's body
Here is the code:
def celsius_fahrenheit(c)
c * 9 / 5 + 32
end
puts 'Enter C:'
c = gets.to_f
puts celsius_fahrenheit(c)

Related

assigning a method result to a variable in ruby

I'm sure it would be hard to find an easier question, but I'm a complete newbie. I have searched extensively and for some reason can't find the answer to this. Here's my code:
puts "Enter F for Fahrenheit and C for Celsius."
x = gets.chomp.downcase
def ftoc(fahrenheit)
(fahrenheit.to_f - 32.0) * (5.0 / 9.0)
end
if x == "f"
puts "Enter your temp:"
temp = gets.chomp.to_i
ftoc temp
elsif x == "c"
puts "Enter your temp:"
temp = gets.chomp.to_i
ctof temp
else
puts "That does not compute."
end
I'm just trying to get the returned result of the method into a variable so I can use it elsewhere....
Remember that calls like ctof temp just initiate a method and then, as you're not putting the result anywhere, discard it immediately.
To clean up this code let's organize it better:
# Temperature conversion method
def ftoc(fahrenheit)
(fahrenheit.to_f - 32.0) * (5.0 / 9.0)
end
# User input method
def temperature_prompt!
puts "Enter F for Fahrenheit and C for Celsius."
x = gets.chomp.downcase
case (x)
when "f"
puts "Enter your temp:"
temp = gets.chomp.to_i
ftoc temp
when "c"
puts "Enter your temp:"
temp = gets.chomp.to_i
ctof temp
else
puts "That does not compute."
end
end
Now you can make use of the fact that in Ruby things like if and case actually return values. In this case it's the value of the last thing to execute in each block, so that result isn't discarded, it's just passed along:
temp = temperature_prompt!
If you enter an invalid value you get the result of puts which is conveniently nil.
Here's something to consider: Ruby is very good at parsing arbitrary text if you can describe the patterns. Here's a simple input routine:
def temperature_prompt!
puts "Enter degrees (e.g. 8F, 2C)"
case (input = gets.chomp.downcase)
when /(\d+)f/
ftoc $1
when /(\d+)c/
ctof $1
else
puts "That does not compute."
end
end
You could add to those patterns to allow things like -2C and 3.4°F if you wanted.

call a method from another file in ruby

Hello I'm new to programming and I started with ruby. I'm trying to do my first program. I found online this code that generate a dice roll
class Die
def initialize(sides)
#sides = sides
end
def generate_die_roll
rand(#sides) + 1
end
def roll(number=1)
roll_array = []
number.times do
roll_array << generate_die_roll
end
total = 0
roll_array.each do |roll|
new_total = total + roll
total = new_total
end
total
end
end
and I would like to use in they way that if the number generated is inferior o equal to another print something otherwise something else.
It's probably very easy but i'm trying in every way and now I will need some help please.
that's my code:
require "./newdado.rb"
energia_vitale = 30
puts "Lancia un dado scrivendo (D) da sommare alla tua Energia Vitale iniziale di #{energia_vitale} punti"
scelta = gets.chomp
case scelta
when "D"
SIX_SIDED_DIE = "#{Die.new(6)}"
values = Array[]
values.push(SIX_SIDED_DIE.roll)
puts values
if values < 2
puts "c"
else puts "b"
end
end
when I run it i receive this error
C:/Users/fix/workspace/D&D Ruby/energia vitale.rb:11:in <main>': undefined methodroll' for "#":String (NoMethodError)
Sorry to bother the community with this beginner problem
Why as string?
this line
SIX_SIDED_DIE = "#{Die.new(6)}"`
should be something like
die = Die.new(6)
then you can do die.roll

if/else start the function again [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
At the else, where the user didn't input a 1 or 2, the script should start over again after displaying the error message. How can I do that?
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
input = gets
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
elseif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
end
You need to wrap the entire thing in a while loop and initialize the variable input to a value like nil.
The while loop's condition should check if the value is 1 or 2, and it will probably need to be converted to an integer with .to_i since gets will return a string.
# initialize to nil
input = nil
# Check if the current value (integer) is 1 or 2
while !([1,2].include?(input))
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
# Convert the string to an int after getting it as input
input = gets.to_i
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
# elsif here, not elseif!!
elsif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
end
end
In fact, rather than a while loop, using an until loop (which Ruby has unlike many other languages) is more readable when testing for a negative condition:
until [1,2].include?(input)
...
end
The [1,2].include?(input) is a slicker way of writing
if input == 1 || input == 2
... that is easily expanded for additional values in the array.
This is it using a function.
puts "Do you want to calculate celcius to fahrenheit (1) or fahrenheit to celcius(2)"
def convert
input = gets
if input == 1
puts "Please enter degrees in Celcius."
celcius = gets
fahrenheit = (celcius.to_i * 9 / 5) + 32
print "The result is "
print fahrenheit
puts "."
elseif input == 2
puts "Please enter degrees in Fahrenheit."
fahrenheit = gets
celcius = (fahrenheit.to_i / 9 * 5) - 32
print "The result is:"
print celcius
puts "."
else
puts "Please enter option 1 or 2"
convert()
end
end
If input != (2 || 1) could work too.

Ruby gets/puts only for strings?

I'm new to Ruby and am currently working on some practice code which looks like the following:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.chomp
puts 'Your favourite number is ' + num + '?'
puts 'Well its not bad but ' + num * 10 + ' is literally 10 times better!'
This code however just puts ten copies of the num variable and doesn't actually multiply the number so I assume I need to make the 'num' variable an integer? I've had no success with this so can anyone show me where I'm going wrong please?
If you are using to_i, then chomp before that is redundant. So you can do:
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts 'Your favourite number is ' + num.to_s + '?'
puts 'Well its not bad but ' + (num * 10).to_s + ' is literally 10 times better!'
But generally, using "#{}" is better since you do not have to care about to_s, and it runs faster, and is easier to see. The method String#+ is particularly very slow.
puts 'Hello there, Can you tell me your favourite number?'
num = gets.to_i
puts "Your favourite number is #{num}?"
puts "Well its not bad but #{num * 10} is literally 10 times better!"
Use the to_i method to convert it to an integer. In other words, change this:
num = gets.chomp
To this:
num = gets.chomp.to_i
you can also make sure the number that the user is using is an integer this way:
num = Integer(gets.chomp)
but you have to create a way to catch the error in case the user input otherwise like a char, or string so; it is must better to use:
num = gets.chomp.to_i
In case the user put another type of data, num will be equal to 0 like you can see in this test example:
puts "give me a number:"
num = gets.chomp.to_i
if num >3
puts "#{num} es mayor a 3 "
else
puts "#{num} es menor a 3 o 3"
end
This a example of the interaction with that script:
give me a number:
sggd
0 es menor a 3 o 3
nil
I hope this clarify better your point.
I wrote a similar program as yours. Here is how I finally got it to work properly! I had to assign the favorite number to be an integer. Then, in the next line I set the new_fav_num with the value of fav_num +1 and then converted it to string. After that, you can just plug your code into the return statement that you want to say to the user, only you have to convert the first fav_num to a string.
puts "What is your favorite number?"
fav_num = gets.chomp.to_i
new_fav_num = (fav_num + 1).to_s
puts "Your favorite number is " + fav_num.to_s + ". That's not bad, but " +
new_fav_num + " is bigger and better!"
Hope this helps.

How do I preserve my float number in ruby

So I'm trying some code out to convert numbers into strings. However, I noticed that in certain cases it does not preserve the last two decimal places. For instance I type 1.01 and 1.04 for addition and I get back 2.04. If I type just 1.05 it preserves the number and returns it exactly. I get whats going on things are being rounded. I don't know how to prevent it from being rounded though. Should I just consider sending (1.01+1.04) to self as only one input?
Warning! I haven't tried this yet so don't know if its supported:
user_input = (1.04+1.01) #entry from user
user_input = gets.to_f
user_input.to_test_string
What I have so far:
class Float
def to_test_string
cents = self % 1
dollars = self - cents
cents = cents * 100
text = "#{dollars.to_i.en.numwords} dollars and #{cents.to_i.en.numwords} cents"
puts text
text
end
end
puts "Enter two great floating point numbers for adding"
puts "First number"
c = gets.to_f
puts "Second number"
d = gets.to_f
e = c+d
puts e.to_test_string
puts "Enter a great floating number! Example 10.34"
a = gets.to_f
puts a.to_test_string
Thanks for the help! Post some code up so I can try!
First of all: never use float for money — Use Float or Decimal for Accounting Application Dollar Amount?
irb> x = 1.01 + 1.04
=> 2.05
irb> y = x % 1
=> 0.04999999999999982
irb> (y * 100).to_i
=> 4
But if want it VERYVERYVERY much:
irb> (y * 100).round.to_i
=> 5
$ python
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 1.04+1.01
2.0499999999999998
Read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic
Also, what Nakilon said.
This is not a problem with ruby, nor your code (although you need to get rid of .en.numwords); it is a problem with the binary floating point representation.
You should use a Fixnum or Bignum to represent the currency.
eg.
class Currency
def initialize str
unless str =~ /([0-9]+)\.([0-9]{2})/
raise 'invalid currency string'
end
#cents = $1.to_i * 100 + $2.to_i
end
end

Resources