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
|
|
0
|
|
|
|
Reply
|
francis.rammeloo (37)
|
11/15/2008 3:12:22 PM |
|
On Nov 15, 12:12=A0pm, Dolazy <francis.ramme...@gmail.com> wrote:
> 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 =3D print =A0 =A0 =A0 =A0 =A0 -- Store current print funct=
ion as
> oldprint
> print =3D function(s) =A0 =A0 =A0 =A0 =A0 =A0 =A0-- Redefine print functi=
on
> =A0 if s =3D=3D "foo" then
> =A0 =A0 oldprint("bar")
> =A0 else
> =A0 =A0 oldprint(s)
> =A0 end
> end
>
> How would you write the above sample using Ruby?
>
> Grtz,
> Francis
module Kernel
alias_method :old_print, :print
def my_print(*args)
old_print "bar"
end
alias_method :print, :my_print
end
irb(main):017:0> print "hey"
bar
=3D> 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,
--
Luis Lavena
|
|
0
|
|
|
|
Reply
|
luislavena (644)
|
11/15/2008 3:19:35 PM
|
|