How to use a method that is within a class and sums two numbers in Ruby

Asked

Viewed 170 times

1

class Soma

def somar(num1, num2)

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

    puts "O resultado é #{result}"
end

end

summing = sum.new (1, 2)

I can’t understand why the following code doesn’t work.

1 answer

0


First you have to create an instance of the class and then call the desired method. 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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Just note that this makes no sense. You shouldn’t create a class for this, you should do it much simpler and more correctly by separating the calculation from the printing, so:

def somar(num1, num2)
    return num1 + num2
end
 
puts "O resultado é #{somar(1, 2)}"

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I tried to do this way to better fix the use of classes, intended to create more classes for other types of more complex accounts as the result of formulas, only one question, the parentheses after the "Soma.new" is necessary? Thank you, it was much clearer this question of instantiating classes!

  • 2

    Better not fix this, because you are learning wrong. First learn the basics and then go to the most complex. The first thing you should learn about classes is that you should only create them if you have a very good reason for this. In fact, everything is in programming. The less code the better, every thing you add needs good justification. Parentheses are not mandatory in Ruby, but I like to use it to make it clear that it is a method and not something else.

  • @Iseeyouthere you can now vote on everything on the site too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.