Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: URI.decode_www_formのサンプルコードでrassocがエラーを出していたので修正 #2884

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

iwtn
Copy link

@iwtn iwtn commented May 18, 2024

問題箇所

URI. decode_www_formのサンプルコードで、エラーが出たので修正しました。

具体的には、以下の部分を実行すると

require 'uri'
ary = URI.decode_www_form("a=1&a=2&b=3")
p ary.rassoc('a').last

以下のようなエラーが出ます。

before.rb:3:in `<main>': undefined method `last' for nil (NoMethodError)

  p ary.rassoc('a').last
                   ^^^^^

原因

これは Array#rassoc の動作として、配列の配列に対して要素の配列でインデックス 1 の要素が obj に等しいものを検索し見つかった最初の要素を返すので、'a' に該当する要素が無いために nil が返り、last が呼び出せなくなっています。

https://docs.ruby-lang.org/ja/latest/method/Array/i/rassoc.html

修正内容

インデックス 1 の要素である '2'rassoc の引数に指定し、 last のままだと引数がそのまま返ってしまうので、インデックス0の値が返るように first を呼び出すようにしました。
また、メソッド名が1文字長くなったので、インデントを揃えました。

修正後

以下のように動作します。

require 'uri'
ary = URI.decode_www_form("a=1&a=2&b=3")
p ary.rassoc('2').first
"a"

@iwtn iwtn changed the title URI.decode_www_formのサンプルコードでrassocがエラーを出していたので修正 fix: URI.decode_www_formのサンプルコードでrassocがエラーを出していたので修正 May 19, 2024
@znz
Copy link
Member

znz commented May 20, 2024

重複したキーに対応する複数の値のうち、最初以外を取り出す例にしたいように見えるので、値からキーを取り出す例になるとうれしくなさそうな気がします。
(例として間違っているのは別の問題なので、待ってみて特に代案がなければとりあえずこのままマージする予定です。)

@iwtn
Copy link
Author

iwtn commented May 22, 2024

重複したキーに対応する複数の値のうち、最初以外を取り出す例にしたいように見えるので、値からキーを取り出す例になるとうれしくなさそうな気がします。

そうですね。確かに。ちょっと考えてみます。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants