Forum: Ruby Ruby equivalent for Lua first-class functions?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Dolazy (Guest)
on 2008-11-15 17:16
(Received via mailing list)
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
Luis L. (Guest)
on 2008-11-15 17:20
(Received via mailing list)
On Nov 15, 12:12 pm, Dolazy <removed_email_address@domain.invalid> wrote:
>   else
>     oldprint(s)
>   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
=> 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,
This topic is locked and can not be replied to.