J
John Lane
Hello,
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. This makes the
statement returning the value of "rights" to fail because there is no
method local variable called "rights".
I can do this instead
def rights_for_item (rights_hash, item)
rights = Array.new
rights_hash.each { |k,v| rights << k if v.include? item }
rights
end
The problem is this returns an empty array rather than nil if no matches
are found. So I do this:
def rights_for_item (rights_hash, item)
rights = Array.new
rights_hash.each { |k,v| rights << k if v.include? item }
rights.empty? ? rights : nil
end
But I don't think it is good idiomatic ruby code. Is there a better way
to write this type of thing ?
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. This makes the
statement returning the value of "rights" to fail because there is no
method local variable called "rights".
I can do this instead
def rights_for_item (rights_hash, item)
rights = Array.new
rights_hash.each { |k,v| rights << k if v.include? item }
rights
end
The problem is this returns an empty array rather than nil if no matches
are found. So I do this:
def rights_for_item (rights_hash, item)
rights = Array.new
rights_hash.each { |k,v| rights << k if v.include? item }
rights.empty? ? rights : nil
end
But I don't think it is good idiomatic ruby code. Is there a better way
to write this type of thing ?