https://github.com/svenfuchs/obj
Struct replacement
https://github.com/svenfuchs/obj
objects ruby struct
Last synced: 3 months ago
JSON representation
Struct replacement
- Host: GitHub
- URL: https://github.com/svenfuchs/obj
- Owner: svenfuchs
- License: mit
- Created: 2019-04-22T17:00:38.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2022-11-02T22:47:31.000Z (over 2 years ago)
- Last Synced: 2025-03-08T23:17:11.034Z (4 months ago)
- Topics: objects, ruby, struct
- Language: Ruby
- Size: 4.88 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# Obj [](https://travis-ci.org/svenfuchs/obj)
A Struct replacement that allows default arguments, and omits the
hash-style API that Struct implements.## Installation
```
gem install ruby-obj
```## Usage
```ruby
require 'obj'class One < Obj.new(:one, two: :default)
endobj = One.new(1)
obj.one # => 1
obj.one? # => true
obj.two # => :default
obj.two? # => trueobj = One.new(nil)
obj.one? # => false
```Modules included to `Obj` are propagated to all instances:
```ruby
module Foo
def foo
end
endObj.include(Foo)
class One < Obj.new(:one)
endone = One.new(1)
one.respond_to?(:foo) # => true
```# Benchmark
`Obj` is marginally slower than `Struct` (which is implemented in C):
```ruby
require 'benchmark'
require 'obj'n = 1_000_000
str = Struct.new(:foo)
obj = Obj.new(:foo)Benchmark.bm(10) do |b|
b.report('str:') { n.times { str.new(:foo).foo } }
b.report('obj:') { n.times { obj.new(:foo).foo } }
end
``````
user system total real
str: 0.180000 0.000000 0.180000 ( 0.174254)
obj: 0.180000 0.000000 0.180000 ( 0.181985)
```