Helpful Information
 
 
Category: Ruby & Ruby On Rails
New to Ruby from Java

Hi

I'm new to Ruby but have some experience in Java. To try and get to grips with Ruby I've been playing around with it and trying to make some old classes I wrote in Java to work in Ruby.

This is a bare-bones class I wrote in Java:


public class Helper {
//attributes
private String name;
private String address;
private String telephone;

public Helper(String name, String address, String telephone) {
//constuctor
this.name = name;
this.address = address;
this.telephone = telephone;
}
//Followed by appropriate getter/setters and methods/main() etc.

This is what I done so far in Ruby and seems to work:



class Helper
attr_accessor :name, :address, :telephone

def initialize (name, address, telephone)
@name = name
@address = address
@telephone = telephone
end

end

The part that is confusing me is making the attributes private as in my Java code, and then doing the suitable getter/setter methods to go with it. I'm not sure how to lay the code out?

If anyone could offer some advice or point me in the direction of a good newbie guide, I'd be much abliged!

Many thanks

Gak

I don't know of any newbie guides, but I can explain the getter/setter stuff.

Instance variables are private by default in Ruby, so all you have to do to make the class in your example equivalent to the Java class is remove the attr_accessor line.

attr_accessor, along with attr_reader and attr_writer are shortcuts for the simplest possible getter and setter methods:



attr_reader :name
# (read public) equivalent to =>
# def name
# return @name
# end
attr_writer :address
# (write public) equivalent to =>
# def address=(address)
# @address = address
# end
attr_accessor :telephone
# (read and write public) equivalent to a combination of attr_reader
# and attr_writer


If you want to provide your own getter or setter to provide additional functionality or to make virtual attributes or whatever, simply take out the shortcut, or change it to provide only the other type of accessor, and write your own:



# Methods that end in = are lvalue eligible, so you can do
# class_instance.telephone = 1231234
# to call this
def telephone=(telephone)
raise Exception.new('Yeah right') if telephone == 5551212
@telephone = telephone
end

# allow classinstance.address
def address
return @address.upcase
end

Thank you very much for your help - much appreciated indeed!!!

I wish the 'Beginning Ruby' book I'm reading had explained things as well as that :)

You're welcome. I hope you're enjoying Ruby, or at least that you will after you get over the steep part of the learning curve.










privacy (GDPR)