On Sep 19, 2012, at 10:29 AM, Jeroen Lodewijks wrote:

> Thanks for the answer.
>=20
> The problem with this code is that this variable is accessible from=20
> outside.
> Let me elaborate what I tried to do. I have code like this:
> (Not saying this good code, I a messing around at the moment)
>=20
> class Card
>  attr_accessor :suit

This is just "shorthand" for:

  def suit
    @suit
  end
  def suit=3D(value)
    @suit =3D value
  end

If you want these instance variables internal, just don't create the =
accessors for them (either implicily or explicitly).

>  attr_accessor :value
>  attr_accessor :name
>  attr_accessor :picture
>  attr_accessor :hcp
>=20
>  def new(value, suit)
>    @value =3D value
>    @suit =3D suit
>  end
>=20
>  def hcp()
>    return @hcp
>  end
> end
>=20
> class Deck
>  require '.\Card'
>  @deck =3D []
>  @@suits =3D ['C', 'D', 'H', 'S']
>  @@values =3D ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q',=20=

> 'K', 'A']
>=20
>  def new(passes =3D 7)
>    @@suits.each do |suit|
>      @@values.each do |value|
>        @deck.push =3D Card.new(suit, value)
>      end
>    end
>    shuffle(passes)
>=20
>    return @deck
>  end
>=20
>  def shuffle(no_of_times)
>    max_len =3D @deck.length
>    no_of_times.each do
>      for source in (no_of_time..source)
>        target =3D rand(source+1)
>        @deck[source], @deck[target] =3D @deck[target], @deck[source]
>      end
>    end
>  end
>=20
>  def remove_card
>    return @deck.pop
>  end
>=20
>  def print_all
>    @deck.each do |card|
>      puts card.suit
>      puts card.value
>    end
>  end
>=20
>=20
> require '.\Deck.rb'
>=20
> @deck =3D Deck.new()
> @deck.print_all()
>=20
> When I execute this I get the error:
> in `print_all': undefined method `each' for nil:NilClass =
(NoMethodError)
>=20
> This is exactly the behaviour as described above by OP. I understand =
why=20
> now. The variable is not in scope. But how do I create a 'local'=20
> variable (in my case deck, that can be seen by all methods of the =
class=20
> but not be manipulated from outside?
> Sorry for this basic question but all courses on Ruby classes that I=20=

> could find online, not one example had a provate class varibale. =
Surely=20
> this must be possible?
>=20
> PS funny that a couple of threads below, it is about card tricks :)
>=20
> --=20
> Posted via http://www.ruby-forum.com/.
>=20