Thanks, Robert. I like the idea. It makes the class more general and the
instantiation cleaner.
Marc


On Mon, Aug 4, 2014 at 4:40 AM, Robert Klemme <shortcutter / googlemail.com>
wrote:

> On Mon, Aug 4, 2014 at 7:15 AM, Marc Chanliau <marc.chanliau / gmail.com>
> wrote:
>
> > On Aug 3, 2014, at 6:40 PM, Jakub Subczynski <kubasub12 / gmail.com>
> wrote:
> >
> > There way to do it has been answered. The two main problems that I see
> here
> > are:
> >
> > Problem 1
> > `Input1(new)` ...to create a new `Input1` object, you should call
> > `Input1.new` (i.e. call the new method on the Input1 class)
> >
> > Problem 2
> > the `gets` method is returning a string, so you need to cast the
> variables
> > to integers somewhere (using .to_i) this can be in the class, or on gets
> > (i.e. `gets.to_i`)
>
> In this example it may not make a difference but I would do the
> conversion when the instance variables are set.  Reason: then the data
> members always have the proper type and you detect wrong values early
> on.  Also, it's more efficient in case someone is invoking #sum over
> and over again.  Thusly:
>
> class Input1
>
>   def initialize(n1, n2)
>     @n1 = Integer(n1)
>     @n2 = Integer(n2)
>   end
>
>   def sum
>     @n1 + @n2
>   end
>
> end
>
> puts "Enter first number: "
> n1 = gets
> puts "Enter second number: "
> n2 = gets
>
> puts Input1.new(n1, n2).sum
> # or, more verbose and reusing your variable assignment
> result = Input1.new(n1, n2).sum
> puts result
> # or holding on to the created instance of Input
> data = Input1.new(n1, n2)
> puts data.sum
>
> Note: you do not need #to_s because puts does this implicitly.
>
> I also fixed "problem" 3: using instance variables for input. This is
> of course possible but a local variable seems more appropriate here.
>
> Kind regards
>
> robert
>
>
> --
> [guy, jim].each {|him| remember.him do |as, often| as.you_can - without
> end}
> http://blog.rubybestpractices.com/
>