On Sep 19, 12:19 am, surge <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> I have a line of the form:
>
> x = hash1.reject{ |key,value| !value}.keys.join(',')
>
> That worked fine but then I needed to do the same thing for hash2. So
> I had to add another line like so:
>
> y = hash2.reject{ |key,value| !value}.keys.join(',')
>
> I'm trying go DRY but I can't think of an elegant way to do it -- I'm
> a relative beginner in ruby. A function is an obvious candidate, but
> that's probably my php thinking. Any better way to avoid the
> repetition? Some fancy loop?
>
> Thanks!
> Sergei
Perhaps extending Hash would help:
# lib/hash.rb
class Hash
def get_non_empty_keys # use whatever name is appropriate
self.reject{|k, v| !v}.keys.join(',')
end
end
# config/environment.rb
require "lib/hash.rb"
You can now use the get_non_empty_keys function on your hashes:
x = hash1.get_non_empty_keys
y = hash2.get_non_empty_keys
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---