Russ Bateman
Russ Bateman

Reputation: 18653

Equivalent operations on instance of Ruby class (to Java)

I'm a Java and long-time C guy trying to learn Ruby. It's a humbling experience to say the least.

I have the following class.

class Node
  @@normal
  def get_normal( n )
    @@normal[ :#n ]
  end
  def add_normal( n, value )
    @@normal[ :#{n} ] = value
  end
end

...and I'm trying to use it probably in a way that only a Java guy would, but perhaps you can set me straight. (In Java I would have:

class Node
{
   private Map< String, String > normal = new HashMap< String, String >();

   public void addToNormal( String key, String value ) { this.normal.put( key, value ); }
   public String getNormal( String key )               { return this.normal.get( key ); }
}
...
Node node = new Node();
node.addToNormal( "city", "New Orleans" );
System.out.println( node.getNormal( "city" );

)

Below, I think I'm trying to get "New Orleans" out of it, but it doesn't work. (Note: On purpose I'm trying to use Ruby symbols instead of strings for the key.)

irb(main):001:0> class Node
irb(main):002:1>   @@normal
irb(main):003:1>   def add_normal( n, value )
irb(main):004:2>     @@normal[ :#{n} ] = value
irb(main):005:3*   end
irb(main):006:3>   def get_normal( n )
irb(main):007:4>     @@normal[ :#n ]
irb(main):008:5*   end
irb(main):009:5> end
irb(main):010:4> node = Node.new()
irb(main):011:4> node.add_normal( :city, "New Orleans" )
irb(main):012:4> puts node.get_normal
irb(main):013:4> puts node.get_normal()

In short, I get nothing out of this.

I would like to incorporate using Ruby symbols as keys in the hash, but the most important thing I want to learn is using a Ruby class in the way I'm using the Java class above. Or, that this is wrong-headed? If you can spare the time, please adjust my class definition and/or what I'm trying to do with it, or generally criticize. Thank you very much!

Upvotes: 1

Views: 76

Answers (1)

ddavison
ddavison

Reputation: 29052

Here is your ruby class,

class Node
  def initialize
    @normal = {}
  end

  def get_normal(n)
    @normal[:n]
  end

  def add_normal(n, value)
    @normal[:n] = value
  end
end

and in your irb,

node = Node.new
node.add_normal(:city, "New Orleans")
puts node.get_normal(:city)

Couple notes,

  • you want to use instance variables, not a class variable for something like that. Instance variables are @my_var and class variables are @@my_var

If you leave @normal = {} at the class level, it'll be nil at the time of execution, so you put in the def initialize which is the constructor for the class.

Upvotes: 1

Related Questions