项目作者: svenfuchs

项目描述 :
Struct replacement
高级语言: Ruby
项目地址: git://github.com/svenfuchs/obj.git
创建时间: 2019-04-22T17:00:38Z
项目社区:https://github.com/svenfuchs/obj

开源协议:MIT License

下载


Obj Build Status

A Struct replacement that allows default arguments, and omits the
hash-style API that Struct implements.

Installation

  1. gem install ruby-obj

Usage

  1. require 'obj'
  2. class One < Obj.new(:one, two: :default)
  3. end
  4. obj = One.new(1)
  5. obj.one # => 1
  6. obj.one? # => true
  7. obj.two # => :default
  8. obj.two? # => true
  9. obj = One.new(nil)
  10. obj.one? # => false

Modules included to Obj are propagated to all instances:

  1. module Foo
  2. def foo
  3. end
  4. end
  5. Obj.include(Foo)
  6. class One < Obj.new(:one)
  7. end
  8. one = One.new(1)
  9. one.respond_to?(:foo) # => true

Benchmark

Obj is marginally slower than Struct (which is implemented in C):

  1. require 'benchmark'
  2. require 'obj'
  3. n = 1_000_000
  4. str = Struct.new(:foo)
  5. obj = Obj.new(:foo)
  6. Benchmark.bm(10) do |b|
  7. b.report('str:') { n.times { str.new(:foo).foo } }
  8. b.report('obj:') { n.times { obj.new(:foo).foo } }
  9. end
  1. user system total real
  2. str: 0.180000 0.000000 0.180000 ( 0.174254)
  3. obj: 0.180000 0.000000 0.180000 ( 0.181985)