jpw
jpw

Reputation: 19247

How create new instance of a Ruby Struct using named arguments (instead of assuming correct order of arguments)

Given: Customer = Struct.new(:name, :address, :zip)

Is there a way to name the arguments instead of presuming a certain order?

The docs say do it like this:

joe = Customer.new("Joe Smith", "123 Maple, Anytown NC", "12345")

which IMO makes it too easy to switch two parameters accidentally.

I'd like to do something like this:

joe = Customer.new(name: "Joe Smith", address: "123 Maple, Anytown NC", zip: "12345")

so that the order is not important:

joe = Customer.new(zip: "12345", name: "Joe Smith", address: "123 Maple, Anytown NC")

Upvotes: 0

Views: 97

Answers (1)

pgblu
pgblu

Reputation: 702

Named parameters are not (yet) possible in Ruby's Struct class. You can create a subclass of your own in line with this Gist: https://gist.github.com/mjohnsullivan/951668

As you know, full-fledged Classes can have named parameters. I'd love to learn why they aren't possible with Structs... I surmise that someone on the Core team has thought of this and rejected it.

Upvotes: 2

Related Questions