RubyTapas #011 - #015
011 Method and Message
??
多分もう何回か見てもピンと来ない。理解不能だ。
- A message is a name for a responsibility which an object may have.
- A method is a named, concrete piece of code that encodes one way a responsibility may be fulfilled. You might say that it is one method by which a message might be implemented.
が大事そう
method & call
puts [1,2,3].reverse
m = [1,2,3].method(:reverme)
puts "---"
puts s.call
みたいなことができることは分かった
012 #fetch for Defaults
★
fetch2回目
auth['info'].fetch('email'){ 'anonymous@example.org' }
fetchにブロックを渡すと失敗した時に、デフォルト値を与えたり、別のエラーを出すなどのことができる
fetchとfalse
|| だとfalseとかnilとかが来た時に期待しない結果になる事がある
{}[:foo] || :default # => :default
{foo: nil}[:foo] || :default # => :default
{foo: false}[:foo] || :default # => :default
Interesting
{}.fetch(:foo){:default} # => :default
{foo: nil}.fetch(:foo){:default} # => nil
{foo: false}.fetch(:foo){:default} # => false
013 Singleton Objects
?
これも良く分からない
Singleton ObjectsはSingleton Patternとは違うのだよ
みたいなことは言っている
良く分からない
014 super
★
def hello(subject=:default)
if subject == :default
super()
puts "How are you today?"
else
super(subject)
はうまい書き方な気がする
superに引き継いだとき、予期せずブロックも渡され実行されることがあり得て、それを防ぎたい時に無効化出来る書き方
&nil
super(subject, &nil)
015 Advanced #fetch
★★
またfetch
fetchはArrayにも使える
ENVにも使える
port = ENV.fetch('PORT'){ 8080 }.to_i
Nested hashにも使える
config2.fetch(:database){{}}.fetch(:type){'sqlite'}
実は引数2つでデフォルトが定義できる
{}.fetch(:threads, 4) # => 4
しかし、作者は個人的には使わない(Never)らしい
なるほど、引数の2つめの場合は、必ずevalされるから、重い内容がデフォルトになった時にパフォーマンスの問題になるらしい。