In my previous post I used classes and used getters and setters like we did in the good old Java days. But as Jak Charlton (Thanks for all his help). pointed out there are other ways to do the getter-setter thing in Ruby.


First of all there are accessors . I think an accessor is like an automatic property in .Net.

In Ruby the accessors like in VB.Net use nicely named backing fields so you can still use them in your code if you like. This is not true in C#.

So I can leave in the getter and setter and just add the accessor and everything should just work.

Here is how the class now looks.

```ruby class Plant def initialize @name = “test” end

attr_accessor :name

def get_name return @name end

def set_name(name) @name = name end end``` And here are my tests to prove it.

```ruby require ‘rubygems’ gem ‘test-unit’ require “test/unit” require_relative “plant”

class Test_plant < Test::Unit::TestCase

def test_if_plant_has_name my_plant = assert_equal(“test”, my_plant.get_name,“Plant has the wrong name”) end

def test_if_name_can_be_set my_plant = my_plant.set_name(“new name”) assert_equal(“new name”,my_plant.get_name,“Plant has the wrong name”) end

def test_if_plant_has_name_accessor my_plant = assert_equal(“test”,,“Plant has the wrong name”) end

def test_if_name_can_be_set_by_name_accessor my_plant = = “new name” assert_equal(“new name”,,“Plant has the wrong name”) end end```


Properties are also available in Ruby, but in this case more as automatic properties than as normal properties. They are easier to use than in C#.