All right! After dabbling around in Java for more than a decade now, working in C++, Lisp and Smalltalk even before that, it's now time to expand the horizon a bit and get my hands on Ruby.
It's promised to make things easier, faster and to speed up the development process significantly.
Assuming you have some deeper knowledge about object-orientation in general and in Java in particular, let's start with a simple example: A trivial Java class vs. its version in Ruby.
Here it is in Java - I won't use comments to save some space:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return "A person named " + name + " aged " + age;
}
}
Nothing special here, just two instance fields, "name" is read-only (just a get method) and "age" is read/write (both get and set method).
In Ruby this seems to be a bit more condensed:
class Person
attr_reader :name, :age
attr_writer :age
def initialize(name, age)
@name = name
@age = age
end
def to_s
"A person named #{@name} aged #{@age}"
end
end
Yep! It is more "condensed". Two reasons: No static typing (I love that!) and the nice idea of declaring the accessibility of a variable directly (attr_reader means read access, attr_writer means write access).
Also nice: Disambiguating instance fields by the "@" prefix - makes is optically clear you're referring to the instance field and not any old identifier that suddenly "slipped into the scope".
Mains and stuff: next post.
CU
No comments:
Post a Comment