I'm sure it does, but I can write the same class in C# just as easily:
class Person
{
public int Sanity { get; set; }
public Person()
{
Sanity = 50;
}
}
And to call it:
var programmer = new Person();
programmer.Sanity += 1000000;
Console.WriteLine(programmer.Sanity);
I don't see much difference between Person.new and new Person();.
What are the real ways in which it will knock my socks off?
I'm honestly asking. Even though I program C# at work, I'm very interested in the advantages of other languages.
Getters and setters that have no logic are pointless. In Go I would write:
type Person struct {
Sanity int
}
func NewPerson() *Person {
return &Person{Sanity: 50}
}
This is good enough 90% of the time (and faster), but if I was writing a library package and I wanted to care about protecting with some logic and care about my export signature:
type Person interface {
Sanity()
SetSanity(val int)
}
type person struct {
sanity int
}
func NewPerson() Person {
return &person{sanity: 50}
}
func (p *person) Sanity() {
return p.sanity
}
func (p *person) SetSanity(val int) {
if val > SOME_FOO1 && val < SOME_FOO2 {
p.sanity = val
}
}
Ruby really is a great language. The author just posted a poor example that is frankly NOT idiomatic Ruby. The proper way to create a getter and setter method on an instance variable is like so:
class Person
attr_accessor :sanity
def initialize
@sanity = 50
end
end
All the attr_* class methods do is define precisely the instance methods the author wrote by hand. Indeed, if attr_reader, attr_writer, and attr_accessor weren't part of Ruby's Module class you could write them yourself, like so: https://gist.github.com/jfarmer/6b4deeb8bcfbe030f876
If using an "eval" method seems smelly to you, you can achieve the same result in pure Ruby using define_method, instance_exec, and instance_variable_get. There are good practical reasons to use module_eval, though.
Regardless, I think the author's point was more that there's nothing "special" about getters and setters in Ruby. They're just plain ol' methods. As a class of methods we write them often enough that we've also defined a higher-order method that takes an instance variable name as input and dynamically defines those getters and setters on the underlying object.
We wouldn't "lose" anything by not having attr_reader and friends, though. Our code would just be slightly more verbose.
What are the real ways in which it will knock my socks off? I'm honestly asking. Even though I program C# at work, I'm very interested in the advantages of other languages.