1
私のレールアプリでは、私はたくさんの参照を参照してください.to_hash.
それは正確に何ですか?レールアプリで `to_hash`とは何ですか?
def to_hash
serializable_hash
end
私のレールアプリでは、私はたくさんの参照を参照してください.to_hash.
それは正確に何ですか?レールアプリで `to_hash`とは何ですか?
def to_hash
serializable_hash
end
方法は、キーワード引数を持っている場合、Rubyはキーワード引数にハッシュ引数の暗黙的な変換を提供しています。この変換は、オプションの引数を割り当てる前に、そのメソッドの最後の引数にto_hash
を呼び出すことによって実行されます。 to_hash
がHashのインスタンスを返す場合、そのメソッドのキーワード引数としてハッシュが取られます。
実行していることがわからない限り、暗黙の変換方法を実装しないでください。たとえば、#to_hash
メソッドが実装されている(おそらく、「もっときれいな名前」のため#to_h?
より)、最も奇妙な結果を引き起こすことが広く見られます。
def method(arg = 'arg', kw_arg: 'kw_arg')
[arg, kw_arg]
end
# As expected:
method() # => ['arg', 'kw_arg']
method(kw_arg: 'your keyword') # => ['arg', 'your keyword']
# Intended as nicety: implicit hash conversion
method({kw_arg: 'hash kw_arg'}) # => ['arg', 'hash kw_arg']
# But has bad side effects:
o = String.new('example object')
def o.to_hash # Now o responds to #to_hash
{ kw_arg: 'o.to_hash' }
end
method(o)
# => ['arg', 'o.to_hash']
# Ruby thinks that o is a Hash and converts it to keyword arguments -.-
method(o, o)
# => ['example object', 'o.to_hash']
# Same here, but since only the *last* argument is converted,
# the first is properly assigned to the first optional argument
通常、ハッシュへの明示的な変換に必要なときは、to_hashを定義しないでください。代わりにto_hを定義してください。