class MyClass def method end end
- prefix methods with the class name to make classmethods
- alternatively, prefix with
- another option is defining within a nested
class << selfclass 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)
!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
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 sectionsclass MyClass def method # default is public end protected def protected_method end private def private_method end public def public_method end end
You can define this like attr_accessorsclass MyClass def method1; end def method2; end protected :method1, :method2 end
You can also define this before the methodclass MyClass private def foo; end end
- make sure to look into ruby standard mixins like
inspect object-id/info (like python's repr) to_s to string
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, b
Un-define a method.
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'
taplets 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