From: Brian Candler Date: 2010-04-15T23:17:10+09:00 Subject: Re: Blocks and local variable creation John Lane wrote: > I have a simple method: > > def rights_for_item (rights_hash, item) > rights_hash.each { |k,v| (rights ||= []) << k if v.include? item } > rights > end > > This does not work because "rights" is created local to the block on > "rights_hash.each" instead of local to the method itself. Just prepare it outside the block first: def rights_for_item(...) rights = nil rights_hash.each { ... } rights end > But I don't think it is good idiomatic ruby code. Is there a better way > to write this type of thing ? It's arguably more idiomatic to return an empty array than to return nil. It's more consistent from the user's point of view. e.g. they can do if rights_for_item(x).include? "update" .. do something end If there is a possibility of returning nil then it is more awkward: r = rights_for_item(x) if r && r.include? "update" .. do something end -- Posted via http://www.ruby-forum.com/.