Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call instance method from another instance method of the same class?

Tags:

ruby

I'm learning Ruby and I'm trying to develop a blackjack game.

I create a class and here is the GIST

https://gist.github.com/robypez/7288032

my Hand class create a new hand object for a player (or for the dealer) It's an array, and inside the array every card is defined by an hash with this key :card, :suit, :value

I have a problem with the "compensate_ace_value" method. This method must use the "ace_number" value returned from the instance method ace_number

How can I call an instance method from another instance method inside a class?

I know that I can define an instance valuable that keep track of my ace number, but i want to know if is possible to call an instance method from another instance method inside a class.

My actual solution is to use the instance variable @ace_number and every time i call the method "receive_card" i call the method "is_ace?" on the card and in the result is true i increment the @ace_number variable.

Thank you

like image 518
Roberto Pezzali Avatar asked Feb 15 '23 19:02

Roberto Pezzali


1 Answers

Here is some simple code to answer your subject question of the post.

How to call instance method from another instance method of the same class?

class Foo
  def bar
    11
  end

  def baz
    bar
  end
end

Foo.new.baz # => 11
like image 120
Arup Rakshit Avatar answered May 10 '23 16:05

Arup Rakshit