The Artima Developer Community
Sponsored Link

Java Buzz Forum
Feeling JavaScripty in Ruby

0 replies on 1 page.

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 0 replies on 1 page
dion

Posts: 5028
Nickname: dion
Registered: Feb, 2003

Dion Almaer is the Editor-in-Chief for TheServerSide.com, and is an enterprise Java evangelist
Feeling JavaScripty in Ruby Posted: Nov 7, 2006 2:03 PM
Reply to this message Reply

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

Topic: Pebble 2.0.0 released Previous Topic   Next Topic Topic: Feature Devotion

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use