Forum: Ruby how can call a class method from another class method

39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 Roelof Wobben (Guest)
on 2014-06-14 15:53
(Received via mailing list)
Hello,

I have this

class Calc

    def self.one
      1
     end

    def self.add
       -> (y) { x+y}
     end

end

but when I do

Calc.one.add.one

I see a Nomethoderror because 1 does not have the method add.

Roelof
Dfa0e5f195b6f312006b465809b76b0b?d=identicon&s=25 Emanuele DelBono (Guest)
on 2014-06-14 16:27
(Received via mailing list)
Because the one method returns a Fixnum (1) and Fixnum doesn't have the
method add.
One way to solve that is to store 1 in a class variable and let one
return
self.

Something like:

def self.one
  @@first_number = 1
  self
end

If you are trying to solve the fluentcalculator quiz I have a solution
here:
https://github.com/emadb/kata_and_quiz/blob/master...

bye
ema
39d8572ef267bc6771f1ef52527a9784?d=identicon&s=25 Roelof Wobben (Guest)
on 2014-06-14 17:17
(Received via mailing list)
Emanuele DelBono schreef op 14-6-2014 16:26:
> def self.one
>   @@first_number = 1
>   self
> end

Still it do not work.

I have now this :

class Calc

   def self.one
      @@first_number = 1
      self
   end

   def self.add
     -> (y) {x+y}
   end

end

Calc.one.add.one

And now I see this errror message

main.rb:16:in `': undefined method `one' for #  (NoMethodError)


Roelof
Dfa0e5f195b6f312006b465809b76b0b?d=identicon&s=25 Emanuele DelBono (Guest)
on 2014-06-14 17:32
(Received via mailing list)
Now your problem is the add method that returns a lambda, and lambdas
doesn't have the method one.
Why do you use a lambda? I don't think it could work for what you're
doing,
but maybe some ruby-expert could help us.
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2014-06-15 00:11
> Calc.one.add.one

So you expect one() to return Calc the first time it is called, and then
you expect one() to return an integer the second time it is called?

class Calc
  @register = []
  @count = 0

  class <<self
    attr_accessor :register
  end

  def self.one
    @count += 1
    @register << 1

    if @count == 1
      self
    else
      eval @register.join(" ")
    end
  end

  def self.add
    @register << "+"
    self
  end

end

puts Calc.one.add.one  #=>2
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.