This post originated from an RSS feed registered with Java Buzz
by dion.
Original Post: Feeling JavaScripty in Ruby
Feed Title: techno.blog(Dion)
Feed URL: http://feeds.feedburner.com/dion
Feed Description: blogging about life the universe and everything tech
Latest Java Buzz Posts
Latest Java Buzz Posts by dion
Latest Posts From techno.blog(Dion)
Advertisement
I am sure there is a better way to do this, so please let me know.
It somehow came up that someone wanted to feel JavaScripty when creating objects with methods.
People often follow the pattern below in JavaScript:
{ foo: function() { ... }, bar: function() { ... } }
How about in Ruby? Lucas Carlson talked about dynamically adding methods to classes through their objects in Ruby , and of course it is simple to do:
o = Object.new
def o.foo
puts 'whee'
end
But what if you want to make this more JavaScripty:
x = {:a => lambda { puts 'whee' }, :b => lambda { puts 'foo' }}.to_o
x.a
A simple bit of code did this (without good checking of things):
class Hash
def to_o
o = Object.new
self.each do |k,v|
if v.is_a?(Proc)
o.class.instance_eval do
define_method(k.to_s, v)
end
end
end
o
end
end
Read: Feeling JavaScripty in Ruby