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.
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.newwithout paramaters it will have default values of 1,4,0 but you could do:without passing a value for c and you’d have values of
a = 5andb = 5with by defaultc = 0still.More broadly, in your Ruby code examples above, you are using brackets where not needed. a
def method_namebegins a block, and aendwill finish it. They serve in place of how brackets are traditionally used in other languages. So for your methodgetSumyou can simply doAlso, note
def getSum(camelCase) would typically bedef get_sum(snake_case) in Ruby. Also note in the examples I give above that parenthesis are dropped. They are not needed in Ruby.