1, Ruby has a shortcut: %w does what we need as below:
a = [ 'ant', 'bee', 'cat', 'dog', 'elk' ]
a[0] ! "ant"
a[3] ! "dog"
# this is the same:
a = %w{ ant bee cat dog elk }
a[0] ! "ant"
a[3] ! "dog"
2, change hash default value:
A hash by default returns nil when indexed by a key it
doesn’t contain. Normally this is convenient, as nil means false when used in conditional
expressions. Sometimes you’llwant to change this default. For example, if you’re
using a hash to count the number of times each key occurs, it’s convenient to have the
default value be zero. This is easily done by specifying a default value when you create
a new, empty hash.
histogram = Hash.new(0)
histogram['key1'] ! 0
histogram['key1'] = histogram['key1'] + 1
histogram['key1'] ! 1
3, Code blocks
Code blocks are just chunks of code between braces or between do. . . end.
{ puts "Hello" } # this is a block
do ###
club.enroll(person) # and so is this
person.socialize #
end ###
4, singleton
We’ll arrange things so that the only way to create a logging object is to call MyLogger.create, and
we’ll ensure that only one logging object is ever created.
class MyLogger
private_class_method :new
@@logger = nil
def MyLogger.create
@@logger = new unless @@logger
@@logger
end
end
By making MyLogger’s new method private, we prevent anyone from creating a logging
object using the conventional constructor.
5, Index an array with a negative integer, and it counts from the end.
6, Index array
Finally, you can index arrays using ranges, in which start and end positions are separated
by two or three periods. The two-period form includes the end position, and the
three-period form does not.
7, about block
If the parameters to a block are existing local variables, those variables will be used as
the block parameters, and their values may be changed by the block’s execution. The
same thing applies to variables inside the block: if they appear for the first time in the
block, they’re local to the block. If instead they first appeared outside the block, the
variables will be shared between the block and the surrounding environment.
In this (contrived) example, we see that the block inherits the variables a and b from
the surrounding scope, but c is local to the block (the method defined? returns nil if
its argument is not defined).
a = [1, 2]
b = 'cat'
a.each {|b| c = b * a[1] }
a -> [1, 2]
b -> 2 #it's been changed in block
defined?(c) ! nil
notes: Although extremely useful at times, this feature may lead to unexpected behavior and is hotly debated in the Ruby community. It is possible that Ruby 2.0 will change the way blocks inherit local variables.