Ruby methods
From wikinotes
instance methods
class MyClass def method end end
class methods
- prefix methods with the class name to make classmethods
- alternatively, prefix with
self
- another option is defining within a nested
class << self
class MyClass def MyClass.do_something # static method puts "hi" end def self.do_something_else # static method puts "hello" end class << self # contents are static def do_something_different puts "heya" end end end
dangerous methods (exclamation mark)
- a
!
following a method invocation usually indicates that it will change the object, instead of returning it.
(it is not an operator, it is just another character used).foo = "A STRING" # a string called foo foo.downcase # returns a downcased string foo.downcase! # downcases foo itself
access control
public accessible to everyone protected access is allowed to other instances of the same class (ex. account objects may want to retrieve each other's balances) private accessible limited to current instance only You may define this in sections
class MyClass def method # default is public end protected def protected_method end private def private_method end public def public_method end endAlternatively, you can define this in groups
class MyClass def method1 end def method2 end def method3 end def method4 end public :method1, :method2 protected :method3, :method4 end
magic methods
- make sure to look into ruby standard mixins like
Comparable
as well!
inspect object-id/info (like python's repr) to_s to string
metaprogramming
define methods
# instance methods class Foo define_method :my_instance_method do |a, b:| puts a, b end end Foo.new.bar('a', b: 'b') # prints a, b# class methods class Foo define_singleton_method :bar do |a, b:| puts a, b end end Foo.bar('a', b: 'b') # prints a, bundef
Un-define a method.
alias
Alias allows you to bind a method to a variable.
Even if the method is overridden, the alias still points to the original method.
call method from string
dog.public_send(:bark) # call method 'bark' on 'dog'
builtin methods
tap
tap
lets you modify an object within a block, and assign it to something.
The object being tapped is always returned.This is particularly useful in combination with a copy of an object.
garfield = Cat.new(name: "garfield", age: "8") nermal = garfield.dup.tap do |c| c.name = "nermal" c.age = 2 end