---
title: "Ruby 2.5 allows creating structs with keyword arguments"
description:
  "We can now create structs by passing keyword arguments using a flag
  keyword_init"
canonical_url: "https://www.bigbinary.com/blog/ruby-2-5-allows-creating-structs-with-keyword-arguments"
markdown_url: "https://www.bigbinary.com/blog/ruby-2-5-allows-creating-structs-with-keyword-arguments.md"
---

# Ruby 2.5 allows creating structs with keyword arguments

We can now create structs by passing keyword arguments using a flag keyword_init

- Author: Prathamesh Sonpatki
- Published: January 16, 2018
- Categories: Ruby 2.5, Ruby

In Ruby, structs can be created using positional arguments.

```ruby
Customer = Struct.new(:name, :email)
Customer.new("John", "john@example.com")
```

This approach works when the arguments list is short. When arguments list
increases then it gets harder to track which position maps to which value.

Here if we pass keyword argument then we won't get any error. But the values are
not what we wanted.

```ruby
Customer.new(name: "John", email: "john@example.com")
=> #<struct Customer name={:name=>"John", :email=>"john@example.com"}, email=nil>
```

Ruby 2.5 introduced
[creating structs using keyword arguments](https://bugs.ruby-lang.org/issues/11925).
Relevant pull request is [here](https://github.com/ruby/ruby/pull/1771/files).

However this introduces a problem. How do we indicate to `Struct` if we want to
pass arguments using position or keywords.

Takashi Kokubun
[suggested](https://bugs.ruby-lang.org/issues/11925#journal-68208-private_notes)
to use `keyword_argument` as an identifier.

```ruby
Customer = Struct.new(:name, :email, keyword_argument: true)
Customer.create(name: "John", email: "john@example.com")
```

Matz
[suggested](https://bugs.ruby-lang.org/issues/11925#journal-68295-private_notes)
to change the name to `keyword_init`.

So in Ruby 2.5 we can create structs using keywords as long as we are passing
`keyword_init`.

```ruby
Customer = Struct.new(:name, :email, keyword_init: true)

Customer.new(name: "John", email: "john@example.com")
=> #<struct Customer name="John", email="john@example.com">
```

## Links

- [Human page](https://www.bigbinary.com/blog/ruby-2-5-allows-creating-structs-with-keyword-arguments)
