Java private variables in Ruby


How would I achieve in Ruby what the following line does in Java?:

private BufferedImage buf;

I need a new BufferedImage, but I don't want to initialize it yet.


You don't need to declare things in advance in ruby, and typing is
done dynamically so the ruby equivalent of that statement is basically
an empty line :slight_smile:


Hi Fred

Thanks for answering my question again. I wanted to make it a method
variable because I wanted to initialize it within the scope of a
conditional loop as well as use it later on in the action method.
So ,that's why I thought I should declare it in the scope of the
method. Is there something else I should be doing?


Attributes of a class are private by default. You have to use attr
acessor ang getter to get access to them.

Free Ruby & Rails screencasts

You don't need to declare variables in advance in ruby like you do in
java (1 exception: if you create a variable inside a block it won't be
visible outside the block unless it already existed). If you really
must buf = nil is all you need.


Yea one of the great parts about ruby is how its dynamically typed. If
you want to declare a private variable accessible throughout the class
use an instance variable:

@buf =

or in a local scope (not accessible outside the class):

buf = ...

if you use an instance variable and want to access it outside the class
(public interface):

attr_accessor :buf

that automatically creates "getter" and "setter" for @buf which look

def buf

def buf=(value)

Hi --

Attributes of a class are private by default. You have to use attr
acessor ang getter to get access to them.

Or, to put it slightly differently: An object's instance variables are
only visible to that object (i.e., only visible when 'self' is that
object). If you expose an instance variable through getter and/or
setter methods, then you've given your object an "attribute", though
there's no real distinction between getter/setter methods that are
implemented as simple wrappers around instance variables and those
that aren't.

So instance variables are not, themselves, attributes; they're just
instance variables, and they can (but do not have to) participate in
the creation of attributes. And there's no language-level difference
between an "attribute" and a getter and/or setter method in general
(whether it uses instance variables or not).