January 21, 2015

Ten Ruby Things I Learned This Week

By Friday my browser is tabbed full of must know information. Time to purge.

1. Monkey Patch a Method and then Call it with Map via Block’s Symbol

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!!!"]

2. Super Short Syntex for If/Else Statement

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"

3. Array.new with an Argument and Block

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] ]

4. Spaceship Operator

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.

5. Know thy Self

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!

6. Blocks and Methods

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}

7 An Abstraction Exercise

Understanding some Enumerable methods by implementing them in Ruby

def question
  return 

8 Common Rails Mistakes

10 common rails mistakes: a best practice tutorial