1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Object.in?でArgumentErrorが発生した場合の対処(Rails3 => Rails4)

Posted at

Rails3 で開発されたアプリケーションを Rails4 対応しようとすると度々例外が発生するようになります。
object.in? もそのひとつ。
ActiveSupport が提供するメソッドですが、Rails3 で引数を二つ以上使っていた場合、Rails4 に上げると以下の例外が発生します。

ArgumentError - wrong number of arguments (2 for 1):

見ての通り、引数ひとつしか使えないのにふたつ使っていることが原因です。
コードを見てみると以下のようになっています。

lib/active_support/core_ext/object/inclusion.rb
  # Returns true if this object is included in the argument. Argument must be
  # any object which responds to +#include?+. Usage:
  #
  #   characters = ["Konata", "Kagami", "Tsukasa"]
  #   "Konata".in?(characters) # => true
  #
  # This will throw an ArgumentError if the argument doesn't respond
  # to +#include?+.
  def in?(another_object)
    another_object.include?(self)
  rescue NoMethodError
    raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
  end

コメントに分かりやすい例が書いてあるのでこれに従えばいいです。
つまり、以下のように修正します。

object_in.rb

object.in?('hogehogehoge', 'fugafugafuga')
    
object.in?(['hogehogehoge', 'fugafugafuga'])

分かってしまえば簡単ですね。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?