Skip to content

Instantly share code, notes, and snippets.

@amitsavani
Last active April 29, 2021 06:24
Show Gist options
  • Select an option

  • Save amitsavani/c030ed4d908caed96c69c7b8560e852f to your computer and use it in GitHub Desktop.

Select an option

Save amitsavani/c030ed4d908caed96c69c7b8560e852f to your computer and use it in GitHub Desktop.
TIL - Use Struct over OpenStruct for performance
2.7.2 :001 > params_1 = { x: 10, y: 15 }
=> {:x=>10, :y=>15}
2.7.2 :002 > params_2 = { x: 10, y: 15, z: 25 }
=> {:x=>10, :y=>15, :z=>25}
2.7.2 :003 > require "ostruct"
=> true
2.7.2 :004 > OpenStruct.new params_1
=> #<OpenStruct x=10, y=15>
2.7.2 :005 > OpenStruct.new params_2
=> #<OpenStruct x=10, y=15, z=25>
2.7.2 :001 > params_1 = { x: 10, y: 15 }
=> {:x=>10, :y=>15}
2.7.2 :002 > params_2 = { x: 10, y: 15, z: 25 }
=> {:x=>10, :y=>15, :z=>25}
2.7.2 :003 > Person = Struct.new(:x, :y, keyword_init: true)
=> Person(keyword_init: true)
2.7.2 :004 > Person.new params_1
=> #<struct Person x=10, y=15>
2.7.2 :005 > Person.new params_2
Traceback (most recent call last):
6: from /home/amit/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `<main>'
5: from /home/amit/.rvm/rubies/ruby-2.7.2/bin/irb:23:in `load'
4: from /home/amit/.rvm/rubies/ruby-2.7.2/lib/ruby/gems/2.7.0/gems/irb-1.2.6/exe/irb:11:in `<top (required)>'
3: from (irb):6
2: from (irb):6:in `new'
1: from (irb):6:in `initialize'
ArgumentError (unknown keywords: z)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment