0

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")
3
  • If it doesn't have to be a struct you could consider ostruct, e.g., stackoverflow.com/a/11962369/438992. There are performance issues, but they don't necessarily matter. Commented Jun 1, 2015 at 17:23
  • i considered openstruct but AFAIK it does not provide the protection against accidentally mis-named keys, for example one could accidentally set namezzzz: "John doe" and it would create a new (wrong) attribute, whereas if you tried that with a Struct it would alert you by throwing an exception (as desired). Commented Jun 1, 2015 at 20:13
  • Yep, that's a definite disadvantage. Commented Jun 1, 2015 at 20:15

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The NamedStruct is nice although I think *args is not needed since you are excluding everything after the first argument. eg. def initialize attributes would function equivalently without having to pack them into an Array and to_hash could be simplified to members.each_with_object({}) {|m,obj| obj[m] = self[m]}
Good point, yes. To be clear, it's not my gist - credit where credit's due.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.