Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 738077
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T07:47:43+00:00 2026-05-14T07:47:43+00:00

I find myself using hash arguments to constructors quite a bit, especially when writing

  • 0

I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. What I end up doing is something like the following:

class Example

    PROPERTIES = [:name, :age]

    PROPERTIES.each { |p| attr_reader p }

    def initialize(args)
        PROPERTIES.each do |p|
            self.instance_variable_set "@#{p}", args[p] if not args[p].nil?
        end
    end

end

Is there no more idiomatic way to achieve this? The throw-away constant and the symbol to string conversion seem particularly egregious.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T07:47:43+00:00Added an answer on May 14, 2026 at 7:47 am

    You don’t need the constant, but I don’t think you can eliminate symbol-to-string:

    class Example
      attr_reader :name, :age
    
      def initialize args
        args.each do |k,v|
          instance_variable_set("@#{k}", v) unless v.nil?
        end
      end
    end
    #=> nil
    e1 = Example.new :name => 'foo', :age => 33
    #=> #<Example:0x3f9a1c @name="foo", @age=33>
    e2 = Example.new :name => 'bar'
    #=> #<Example:0x3eb15c @name="bar">
    e1.name
    #=> "foo"
    e1.age
    #=> 33
    e2.name
    #=> "bar"
    e2.age
    #=> nil
    

    BTW, you might take a look (if you haven’t already) at the Struct class generator class, it’s somewhat similar to what you are doing, but no hash-type initialization (but I guess it wouldn’t be hard to make adequate generator class).

    HasProperties

    Trying to implement hurikhan’s idea, this is what I came to:

    module HasProperties
      attr_accessor :props
      
      def has_properties *args
        @props = args
        instance_eval { attr_reader *args }
      end
    
      def self.included base
        base.extend self
      end
    
      def initialize(args)
        args.each {|k,v|
          instance_variable_set "@#{k}", v if self.class.props.member?(k)
        } if args.is_a? Hash
      end
    end
    
    class Example
      include HasProperties
      
      has_properties :foo, :bar
      
      # you'll have to call super if you want custom constructor
      def initialize args
        super
        puts 'init example'
      end
    end
    
    e = Example.new :foo => 'asd', :bar => 23
    p e.foo
    #=> "asd"
    p e.bar
    #=> 23
    

    As I’m not that proficient with metaprogramming, I made the answer community wiki so anyone’s free to change the implementation.

    Struct.hash_initialized

    Expanding on Marc-Andre’s answer, here is a generic, Struct based method to create hash-initialized classes:

    class Struct
      def self.hash_initialized *params
        klass = Class.new(self.new(*params))
      
        klass.class_eval do
          define_method(:initialize) do |h|
            super(*h.values_at(*params))
          end
        end
        klass
      end
    end
    
    # create class and give it a list of properties
    MyClass = Struct.hash_initialized :name, :age
    
    # initialize an instance with a hash
    m = MyClass.new :name => 'asd', :age => 32
    p m
    #=>#<struct MyClass name="asd", age=32>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 454k
  • Answers 455k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer At launch, Java was the only officially supported programming language… May 15, 2026 at 10:00 pm
  • Editorial Team
    Editorial Team added an answer I have this problem often, and I solved it with… May 15, 2026 at 10:00 pm
  • Editorial Team
    Editorial Team added an answer One difference is in how they handle the IFS variable… May 15, 2026 at 10:00 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.