By Friday my browser is tabbed full of must know information. Time to purge.
Source: Rosetta Code
# the monkeypatch
class String
def shout
"#{self}!!!!"
end
end
a = "I like cats"
a.shout # => I like cats!!!
# here is the map, block, symbol part
animals = %w(cats dogs birds )
animals.map(&:shout) # => ["cats!!!", "dogs!!!", "birds!!!"]
Learned while browsing Rosetta Code
# The following blocks are equilivant:
if a == b
puts "match"
else
puts "no match"
end
#is the same as this one.
a == b ? "match" : "no match"
Discovered at Engine Yard
class BallGame
def score_per_innings
@score_per_innings ||= Array.new(9) { Array.new(2) {0} }
end
end
mets_vs_yanks = Ballgame.new
mets_vs_yanks.score => [ [0-0], [0-0], [0-0], [0-0], [0-0], [0-0], [0-0], [0-0], [0-0] ]
Evaluates value a and b. Returns -1 when a follows b, 0 when a == b, and 1 when b follows a
string = %w(b a i c n o)
# the following are equivalant
string.sort.reverse
string.sort {|a, b| b <=> a } #note b precedes a in spaceship block. to match the reverse method.
Stumbled upon at jonathan-alban’s fizz_buzz. Explained at RubyLearning
At every point there is one and only one
self
- the current or default object accessible to you in your program.
class EvalEven
def self.find(number)
if number % 2 == 0
"#{number} is an even number!"
else
"odd number"
end
end
end
EvalEven.find(2) # => 2 is an even number!
You normally invoke a block by using the yield statement from a method that has the same name as that of the block.
def test
yield
end
test { puts "hello world" }
def adder(a,b,c)
yield a, b, c
end
test {|a,b,c| puts a+b+c}
Understanding some Enumerable methods by implementing them in Ruby
def question
return