"CoolCat".underscore #=> "cool_cat" "cool_cat".capitalize #=> "Cool_cat" "cool_cat".camelize #=> "CoolCat"
The file open modes are not really specific to ruby – they are part of IEEE Std 1003.1 (Single UNIX Specification). You can read more about it here:http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html
define your own way to marshal
calling Marshal.dump(Myobj.new(“name”, “v”, “data”)) will call the marshal_dump method in the Myobj class
class MyObj def initialize name, version, data @name = name @version = version @data = data end def marshal_dump [@name, @version] end def marshal_load array @name, @version = array end end
symbol vs. string
as hash keys, string as keys is duped and frozen so it cannot be modified. Keys to be frozen is good, but dup may be expensive.
Element Assignment—Associates the value given by value with the key given by key. key should not have its value changed while it is in use as a key (a
String passed as a key will be duplicated and frozen).
- use the Ruby built-in: defined? It works for constants, methods, classes, etc.
There is no better among these two choices. Choosing which one depends on the user case. The second way specifies the scope to check if the constant exists, while the first way will seek for this constant through the ancestor trees. If you defines two constants with the same name but different values, you’d better use the 2nd way.
- scope of constants:Ruby searches for the constant definition in this order:
- The enclosing scope
- Any outer scopes (repeat until top level is reached)
- Included modules
class C X = 1 module M X = 2 class D X = 3 puts X # => 3 puts C::X # => 1 puts C::M::X # => 2 puts M::X # => 2 end end end
The “super” keyword in ruby behaves a little differently than other languages. Instead of returning an instance of the superclass, it checks all the way up the ancestry tree to find the inherited method.
Is the same as
- supper is a keyword, not a method; Methods can be overridden in subclasses of ruby.
- ancestor tree: An ancestor of a class is either the class itself, a module included by any of the class’s ancestors or the superclass of any of the class’s ancestors. In short the ancestors of a class are all the classes and modules in which ruby will look for the method definition when you call a method on an object of that class.
module Vehicular def move_forward(n) @position += n end end class Vehicle include Vehicular # Adds Vehicular to the lookup path end class Car < Vehicle def move_forward(n) puts "Vrooom!" super # Calls Vehicular#move_forward end end
puts Car.ancestors.inspect # Output # [Car, Vehicle, Vehicular, Object, Kernel, BasicObject]
Note the inclusion of the
To read and make notes http://blog.grayproductions.net/articles/getting_code_ready_for_ruby_19