Preferred method of dealing with options in final argument hash

조회수 18회
읽지 않은 첫 메시지로 건너뛰기

iHiD

읽지 않음,
2012. 5. 17. 오후 1:40:0712. 5. 17.
받는사람 rubyonra...@googlegroups.com
Hi guys,

I'm wondering what the preferred method of parsing the "options" hash is?

In one file, I've just seen these three different methods:

def foobar(options = {})
  options.reverse_merge!(:length => 30)
  #...
  call_another_method(options[:length])
end

def foobar(options = {})
  options[:length] ||= 30
  #...  
  call_another_method(options[:length])
end

def foobar(options = {})
  length = options[:length] || 30
  #...
  call_another_method(length)
end

I'd like to go through and standardise them, at least in the files I'm working on. 

Which is the preferred method?

Thanks,
Jeremy

Donald Ball

읽지 않음,
2012. 5. 17. 오후 1:48:2212. 5. 17.
받는사람 rubyonra...@googlegroups.com
I would strongly advocate using the Hash#fetch method in general:

options.fetch(:length, 30)

Though it's worth noting it gives different results than the || idiom
for nil and false hash values.

-- donald

Jeremy Evans

읽지 않음,
2012. 5. 17. 오후 2:09:5012. 5. 17.
받는사람 rubyonra...@googlegroups.com
It also gives different results if options has a default value or a
default proc.

If the default value is expensive to produce, using the block version
of Hash#fetch may be better for performance, as then it will only
produce the expensive value if the options hash doesn't contain the
option.

It's generally considered bad style to modify arguments passed into a
method unless that is the purpose of the method itself. Using:

options.reverse_merge!(:length => 30)

or

options[:length] ||= 30

modifies the options hash, and that's a bad idea IMO.

Jeremy
전체답장
작성자에게 답글
전달
새 메시지 0개