So, below you can see a simple class written in Ruby:
class MyClass
end
And an object instantiation:
m = MyClass.new
Adding methods is very easy too:
class MyClass
def my_method
puts "That's a Ruby method!";
end
end
If you're using irb (interactive ruby), a tool to execute interactively ruby expressions read from stdin, you don't have to re-instantiate 'm', the changes made in MyClass will affect 'm' dynamically (on the fly), so if you call 'm.my_method', don't worry, it'll work.
If you're not sure about a method in a object, you can do this:
if m.respond_to? "my_method"
m.my_method
end
Do I need to explain something else?
The 'initialize' method represents a constructor in a Ruby class and the parameters come after:
class MyClass
def initialize name = "Hello World!"
@name = name
end
def hello
puts "#{@name}"
end
end
The '@name' is a field, like 'private Object obj;' in Java, and in the case above 'name' has "Hello World!" as its default value.
If you try to call 'm.name' you'll get something like:
NoMethodError: undefined method `name' for ...
This is because name is 'private', to create 'getters' and 'setters' you have to add 'attr_accessor :name' before the constructor. So, after that you can call 'm.name' or 'm.name = "hello"', for example, as you wish.
No comments:
Post a Comment