Jakz Aizzat
Jakz Aizzat

Reputation: 159

How to use simple operator on this?

I'm create some sample code and still begineer class Number

def initialize(name)
    @first = []
    @second = []
    @final = 0

end

def input
    print "Please input first number"
    @first = gets.chomp
    print "Please input second number"
    @second = gets.chomp

end

def output
    @final = @first * @second
    puts @final

end



end

number = Number.new('Jakz')
number.class
number.input
number.output

I want to sum the 2 input number but its give error because the 2 number become a string not a number.How to fix it?

Upvotes: 0

Views: 37

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

gets returns a String. The prompt does not know that you are requesting a number. Calling to_f does its best to convert the string to a floating point number

def input
    print "Please input first number"
    @first = gets.chomp.to_f
    print "Please input second number"
    @second = gets.chomp.to_f

end

be aware that if the user enters something that is not a number - the above code does not validate it, and will most probably set the variables to 0.

Upvotes: 3

Related Questions