Ruby equivalent for Lua first-class functions?

D

Dolazy

I think one of Lua's nice features is that all functions are first-
class functions. That makes it possible to override behavior like
this:

-- Sample stolen from Wikipedia
local oldprint = print -- Store current print function as
oldprint
print = function(s) -- Redefine print function
if s == "foo" then
oldprint("bar")
else
oldprint(s)
end
end

How would you write the above sample using Ruby?


Grtz,
Francis
 
L

Luis Lavena

I think one of Lua's nice features is that all functions are first-
class functions. That makes it possible to override behavior like
this:

-- Sample stolen from Wikipedia
local oldprint = print           -- Store current print function as
oldprint
print = function(s)              -- Redefine print function
  if s == "foo" then
    oldprint("bar")
  else
    oldprint(s)
  end
end

How would you write the above sample using Ruby?

Grtz,
Francis

module Kernel
alias_method :eek:ld_print, :print
def my_print(*args)
old_print "bar"
end
alias_method :print, :my_print
end

irb(main):017:0> print "hey"
bar
=> nil

There are several approaches to achieve the same, that's the beauty or
the curse of Ruby :)

As more complex example, you can check how rubygems replace 'require'
functionality to be able to pick code outside the default $LOAD_PATH.

HTH,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top