From: Rob Biedenharn Date: 2012-09-20T00:25:21+09:00 Subject: Re: Class variables On Sep 19, 2012, at 10:29 AM, Jeroen Lodewijks wrote: > Thanks for the answer. > > The problem with this code is that this variable is accessible from > 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) > > class Card > attr_accessor :suit This is just "shorthand" for: def suit @suit end def suit=(value) @suit = 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 > > def new(value, suit) > @value = value > @suit = suit > end > > def hcp() > return @hcp > end > end > > class Deck > require '.\Card' > @deck = [] > @@suits = ['C', 'D', 'H', 'S'] > @@values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', > 'K', 'A'] > > def new(passes = 7) > @@suits.each do |suit| > @@values.each do |value| > @deck.push = Card.new(suit, value) > end > end > shuffle(passes) > > return @deck > end > > def shuffle(no_of_times) > max_len = @deck.length > no_of_times.each do > for source in (no_of_time..source) > target = rand(source+1) > @deck[source], @deck[target] = @deck[target], @deck[source] > end > end > end > > def remove_card > return @deck.pop > end > > def print_all > @deck.each do |card| > puts card.suit > puts card.value > end > end > > > require '.\Deck.rb' > > @deck = Deck.new() > @deck.print_all() > > When I execute this I get the error: > in `print_all': undefined method `each' for nil:NilClass (NoMethodError) > > This is exactly the behaviour as described above by OP. I understand why > now. The variable is not in scope. But how do I create a 'local' > variable (in my case deck, that can be seen by all methods of the class > but not be manipulated from outside? > Sorry for this basic question but all courses on Ruby classes that I > could find online, not one example had a provate class varibale. Surely > this must be possible? > > PS funny that a couple of threads below, it is about card tricks :) > > -- > Posted via http://www.ruby-forum.com/. >