Hi --

On Thu, 23 Aug 2007, Finn Koch wrote:

> Hi, I'm just learning ruby and I'm working on a server connection.  I
> have the following code:
>
> class IRCBot
>
>   ....
>
>
>   def connect
>      puts "Connecting to #{@server}..."
>      @conn = TCPSocket.new( @server, @port )
>      handle_server_registration
>   end
> end
>
>
> I have another class that needs to perform a '@conn.send("asdf",0)'.
> Can anyone help me figure out how I can have this external class access
> the @conn instance variable?

It can't, at least not directly. However, Ruby provides a very easy
way to wrap instance variables in accessor (get/set) methods. In your
case, it would be something like this:

   class IRCBot
     attr_reader :conn  # "getter" (reader) method wrapped around @conn

     def connect
       puts ...
       # etc.
     end
   end

Now you can do:

   class OtherClass
     def whatever
       bot = IRCBot.new
       bot.conn...   # you now have access to bot's conn attribute
     end
   end

Another way to put this is: Ruby objects can have attributes, which
are readable and/or writeable. From the outside, these are just
methods. From the inside (the class where they're defined), they are
implemented (unless you write a fancier custom version) as wrapper
methods around instance variables.


David

-- 
* Books:
   RAILS ROUTING (new! http://www.awprofessional.com/title/0321509242)
   RUBY FOR RAILS (http://www.manning.com/black)
* Ruby/Rails training
     & consulting:  Ruby Power and Light, LLC (http://www.rubypal.com)