Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.ruby > #3631

Initialize Struct from Hash

From Brian Candler <b.candler@pobox.com>
Newsgroups comp.lang.ruby
Subject Initialize Struct from Hash
Date 2011-04-28 12:00 -0500
Organization Service de news de lacave.net
Message-ID <919600ef40c16b10cb0f01a757234376@ruby-forum.com> (permalink)

Show all headers | View raw


I just want to check I've not missed something here. Is there a built-in
way to initialize a Struct from a hash of key/value pairs?

That is, can I shorten the following?

K1 = Struct.new :foo, :bar

module FixStruct
  def set(h)
    h.each { |k,v| self[k] = v }
    self
  end
end

class K1
  include FixStruct
end

k1 = K1.new.set(:bar=>456, :foo=>123)
p k1

(I'm talking about real Struct here, not OpenStruct etc)

Thanks,

Brian.

-- 
Posted via http://www.ruby-forum.com/.

Back to comp.lang.ruby | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-28 12:00 -0500
  Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:05 -0500
    Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:10 -0500
    Re: Initialize Struct from Hash 7stud -- <bbxx789_05ss@yahoo.com> - 2011-04-28 12:16 -0500
      Re: Initialize Struct from Hash Jesús Gabriel y Galán <jgabrielygalan@gmail.com> - 2011-04-28 12:19 -0500
  Re: Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-28 15:24 -0500
    Re: Initialize Struct from Hash Joel VanderWerf <joelvanderwerf@gmail.com> - 2011-04-28 15:50 -0500
      Re: Initialize Struct from Hash Robert Klemme <shortcutter@googlemail.com> - 2011-04-29 03:06 -0500
        Re: Initialize Struct from Hash Joel VanderWerf <joelvanderwerf@gmail.com> - 2011-04-29 10:27 -0500
      Re: Initialize Struct from Hash Brian Candler <b.candler@pobox.com> - 2011-04-29 03:22 -0500

csiph-web