2

ラムダをプロパティとして取り、そのプロパティがアクセスされたときにそれを呼び出すことができることを除いて、Hashie のように機能する Ruby ライブラリはありますか?

たとえば、次のようなものが欲しいです。

# Lash = Lambda-able hash
lash = Lash.new(
  someProperty:      "Some value",
  someOtherProperty: ->{ Time.now }
)

lash.someProperty      # => "Some value"
lash.someOtherProperty # => 2013-01-25 16:36:45 -0500
lash.someOtherProperty # => 2013-01-25 16:36:46 -0500
4

2 に答える 2

0

これが私の実装です:

class Lash < BasicObject
  def self.new hash
    ::Class.new do
      hash.each do |key, value|
        method_body = if value.respond_to? :call
                        ->(*args){ self.instance_exec(*args, &value) }
                      else
                        ->{ value }
                      end
        define_method(key, &method_body)
      end
    end.new
  end
end
于 2013-01-25T21:38:50.087 に答える
0

私は数日前に似たようなものが欲しかったので、Hashie 2.0.0.beta を使用することになりました。これにより、独自のサブクラスで使用できる拡張機能が提供されますHash

require 'hashie'
require 'hashie/hash_extensions' 

class Lash < Hash
  include Hashie::Extensions::MethodAccess

  def [](key)
    val = super(key)
    if val.respond_to?(:call) and val.arity.zero?
      val.call
    else
      val
    end
  end
end

これにより、次のようなことができます。

l = Lash.new
#=> {}

l.foo = 123
#=> 123

l.bar = ->{ Time.now }
#=> #<Proc:0x007ffab3915f18@(irb):58 (lambda)>

l.baz = ->(x){ 10 * x }
#=> #<Proc:0x007ffab38fb4d8@(irb):59 (lambda)>

l.foo
#=> 123

l.bar
#=> 2013-01-26 15:36:50 +0100

l.baz
#=> #<Proc:0x007ffab38fb4d8@(irb):59 (lambda)>

l.baz[5]
#=> 50

注: これは Hashie 2.0.0.beta でのみ機能し、Gemfile に次の行を追加して Bundler 経由でインストールできます:

gem 'hashie', :git => 'git://github.com/intridea/hashie.git'

または、Bundler を使用しない場合は、specific_installgem を使用します。

gem install specific_install
gem specific_install -l git://github.com/intridea/hashie.git
于 2013-01-26T14:41:07.147 に答える