Ruby Asterisk Operator

No Comments

You’ve all probably created a method with a variable argument length:

def foo(args*)
  puts args.inspect
end

I’ve just stumbled on using the asterisk operator when passing paramaters:

params = [1,2,3]
foo(*params)
#=> [1, 2, 3]
foo(params)
#=> [[1,2,3]]

Has the same result as:

foo('a','b','c')
#=> [1,2,3]

Difference between Proc and Lambda

No Comments

Shamelessly stolen from here.

def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo"
end

def bar
  f = lambda { return "return from lambda" }
  f.call # control does not leave bar here
  return "return from bar"
end

puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"
 pnew = Proc.new {|x, y| puts x + y}
 lamb = lambda {|x, y| puts x + y}

 # works fine, printing 6
 pnew.call(2, 4, 11)

 # throws an ArgumentError
 lamb.call(2, 4, 11)

Ruby Syntax Highlighting

No Comments

By night I secretly hack away at my Ruby on Rails blog (so I can ditch this php thing). I have enjoyed the following code greatly.

def filter_content(content)
      h = Hpricot(content)
      c = Syntax::Convertors::HTML.for_syntax "ruby"
      h.search('//pre[@class="ruby"]') do |e|
          e.inner_html = c.convert(e.inner_text,false)
      end
      h.to_s
end

Older Entries