# Ruby equivalent for Lua first-class functions?

**URL:** <https://www.ruby-forum.com/t/ruby-equivalent-for-lua-first-class-functions/153356>\
**Category:** Ruby\
**Created:** [November 15, 2008, 4:16pm UTC](https://www.ruby-forum.com/t/ruby-equivalent-for-lua-first-class-functions/153356 "2008-11-15T16:16:03Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Dolazy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/eb8c5e/32.png) [@Dolazy](https://www.ruby-forum.com/u/Dolazy)\
**Post date:** [November 15, 2008, 4:16pm UTC](https://www.ruby-forum.com/t/ruby-equivalent-for-lua-first-class-functions/153356/1 "2008-11-15T16:16:03Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Dolazy](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/eb8c5e/32.png) [@Dolazy](https://www.ruby-forum.com/u/Dolazy)\
**Post date:** [November 15, 2008, 4:20pm UTC](https://www.ruby-forum.com/t/ruby-equivalent-for-lua-first-class-functions/153356/2 "2008-11-15T16:20:44Z")

</div>

On Nov 15, 12:12 pm, Dolazy [removed\_email\_address@domain.invalid](mailto: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,
