{{tag>ruby}} ====== 今日のメソッド ====== ===== その1 ===== Railsの''Hash#slice!''から。 def slice!(*keys) omit = slice(*self.keys - keys) # keysは登録ハッシュを出すメソッド。ここでは、[:if, :unless, :on..]などが入っている。*self.keysは引数のこと?引いて…つまりこれらのオプションは無視する、と。 hash = slice(*keys) hash.default = default # defaultも保持する必要がある! hash.default_proc = default_proc if default_proc # procをよくわかっていない。 replace(hash) # ここがメイン。 omit # 画面出力用。副作用にすぎない。 end * sliceの挙動をちょっと変えて、便利にしている。 ''slice!''の例 hash = { a: 1, b: 2, c: 3 } hash.slice!(:a, :b) hash # => {:a=>1, :b=>2} 要するに配列の対応したやつだけ取り出すメソッド。!は破壊的なことをしめす。hash自体が変化している。 ===== その2 ===== ''String#camelize'' def camelize(first_letter = :upper) case first_letter when :upper ActiveSupport::Inflector.camelize(self, true) when :lower ActiveSupport::Inflector.camelize(self, false) else raise ArgumentError, "Invalid option, use either :upper or :lower." end end "mozilla_firefox".camelize # => MozillaFirefox # upper camel case というらしい。 "mozilla_firefox".camelize(:lower) # => mozillaFirefox # lower camel case というらしい。最初だけ小文字。 * '':upper'' か '':lower'' 以外を入れたとき、ちゃんとエラーメッセージが返ってきて親切。 ===== その3 ===== ''default-proc'' そもそもprocがわかってない。 h = Hash.new { |a| h[a] = a*a } # defaultを定義 p = h.default_proc p.call(2) # => 4 p.call(10) # => 100 h # => {2=>4, 10=>100} h = Hash.new { 3 } # defaultを定義 p = h.default_proc p.call # => 3 ===== 4 ===== ''hash#default'' https://www.includehelp.com/ruby/hash-default_proc-method-with-example.aspx hash = Hash.new(33) # => {} hash # => {} hash[:a] # => 33 hash.default # => 33