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 private accessible to current class, and inherited by subclasses protected accessible to the current class, and NOT inherited by subclasses 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 endYou can define this like attr_accessors
class MyClass def method1; end def method2; end protected :method1, :method2 endYou can also define this before the method
class MyClass private def foo; end 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
access methods
Foo.instance_method(:bar) # get instance-method 'Foo#bar' Foo.method(:bar) # get class-method 'Foo.bar'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