Forum: Ruby-core Rails' HashWithIndifferentAccess is incompatible with Ruby's keyword arguments

0525b332aafb83307b32d9747a93de03?d=identicon&s=25 unknown (Guest)
on 2014-04-11 19:15
(Received via mailing list)
Issue #9731 has been updated by Rafael Fran├ža.


Just to be clear this issue is not about `HashWithIndifferentAccess`, it
is about using hash with string keys to be used as keyword arguments
(`HashWithIndifferentAccess` store the keys as strings).

This same script would fail:

```ruby
require 'minitest/autorun'

def sum(a: 0, b: 0)
  a + b
end

class BugTest < MiniTest::Unit::TestCase
  def setup
    @hash_with_symbol_keys = {a: 18, b: 24}
    @hash_with_string_keys = {'a' => 18, 'b' => 24}
  end

  def test_hash_with_symbol_keys
    assert_equal 42, sum(@hash_with_symbol_keys)
  end

  def test_hash_with_string_keys
    assert_equal 42, sum(@hash_with_string_keys)
  end
end
```

----------------------------------------
Bug #9731: Rails' HashWithIndifferentAccess is incompatible with Ruby's
keyword arguments
https://bugs.ruby-lang.org/issues/9731#change-46178

* Author: Konstantinos Karachalios
* Status: Open
* Priority: Normal
* Assignee:
* Category:
* Target version:
* ruby -v: 2.1.1
* Backport: 2.0.0: UNKNOWN, 2.1: UNKNOWN
----------------------------------------
Origin: https://github.com/rails/rails/issues/14643

In Ruby it is possible to use a POR Hash in place of keyword arguments,
making the transition between using an `options = {}` to keyword
arguments easy.

The same is not true for HashWithIndifferentAccess and this makes it
difficult to pass the `params` hash directly to methods with keyword
arguments.

### Bug test
```ruby
require 'active_support/hash_with_indifferent_access'
require 'minitest/autorun'

def sum(a: 0, b: 0)
  a + b
end

class BugTest < MiniTest::Unit::TestCase
  def setup
    @normal_hash = {a: 18, b: 24} # just a hash
    @indiff_hash =
ActiveSupport::HashWithIndifferentAccess.new(@normal_hash)
  end

  def test_ruby_hash
    assert_equal 42, sum(@normal_hash)
  end

  def test_hash_with_indifferent_access
    assert_equal 42, sum(@indiff_hash)
  end
end
```

### Workaround
```ruby
sum(@indiff_args.symbolize_keys)
```

### VERSIONS
* ruby 2.0.0-p353 & activesupport 4.0.1
* ruby 2.1.0-p0 & activesupport 4.0.3
* ruby 2.1.1-p76 & activesupport 4.0.4, 3.2.17
This topic is locked and can not be replied to.