How to use a method that is inside a class and adds two numbers in Ruby

1
class Soma

def somar(num1, num2)

    @num1 = num1
    @num2 = num2
    result = num1 + num2

    puts "O resultado é #{result}"
end

end

adding = soma.new (1, 2)

I can not understand why the following code does not work.

    
asked by anonymous 06.11.2018 / 20:55

1 answer

0

First you have to create an instance of the class and then call the method you want. So:

class Soma
    def somar(num1, num2)
        @num1 = num1
        @num2 = num2
        result = num1 + num2
        puts "O resultado é #{result}"
    end
end

somando = Soma.new()
somando.somar(1, 2)

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

Just notice that this does not make sense. You should not create a class for this, you should do it in a much simpler and more correct way by separating the calculation from the impression, like this:

def somar(num1, num2)
    return num1 + num2
end

puts "O resultado é #{somar(1, 2)}"

See running on ideone . And no Coding Ground . Also put it in GitHub for future reference .

    
06.11.2018 / 20:59