JVK
JVK

Reputation: 3912

Setting default values

I am learning ruby and I am specifically playing with OOPS in it. I am trying to write equivalent of this PHP code in ruby

    class Abc {
        $a = 1;
        $b = 4;
        $c = 0;

        function __constructor($cc) {
            $this->c = $cc
        }

        function setA($v) {
            $this->a = $v
        }

        function getSum() {
            return ($this->a + $this->b + $this->c);
        }
    }

    $m = new Abc(7);
    $m->getSum(); // 12

    $m->setA(10);
    $m->getSum(); // 21

I am trying to write equivalent of above PHP to ruby. Please note my goal is to have default values of soem of the class variable and if I want to override it, then I can do it by calling getter/setter method.

    class Abc 
        attr_accessor :a
        def initialize cc
            @c = cc
        end

        def getSum 
            #???
        end

    end

I don't like to do

Abc.new(..and pass value of a, b and c)

My goal is to have default values, but they can be modified by instance, if required.

Upvotes: 0

Views: 175

Answers (1)

joofsh
joofsh

Reputation: 1655

class Abc
  attr_accessor :a, :b, :c 

  def initialize a = 1, b = 4, c = 0 
    @a = a
    @b = b
    @c = c
  end

end

This will accept 1, 4, and 0 respectively as default values, but they can be overridden by passing in parameters.

So if you do example = Abc.new without paramaters it will have default values of 1,4,0 but you could do:

     example2 = Abc.new 5, 5 

without passing a value for c and you'd have values of a = 5 and b = 5 with by default c = 0 still.

More broadly, in your Ruby code examples above, you are using brackets where not needed. a def method_name begins a block, and a end will finish it. They serve in place of how brackets are traditionally used in other languages. So for your method getSum you can simply do

def get_sum
  #your_code
end

Also, note def getSum (camelCase) would typically be def get_sum (snake_case) in Ruby. Also note in the examples I give above that parenthesis are dropped. They are not needed in Ruby.

Upvotes: 3

Related Questions