Re: Syntax sugar: method[](...) => method(...)





On Jun 29, 4:17 pm, "Erwin Abbott" <erwin.abb...@xxxxxxxxx> wrote:
Hi,

The [] method is really handy when you have an object that should
behave like a hash or array. One thing I find myself wishing I could
also do is something like

def logins[](date)
@events.select{|e| e.action == :login and e.date == date}
end

There may be a better way to deal with this example, but this is just
to demonstrate the circumstances where you don't have an array or hash
called logins, but you'd like to be able to use that [] syntax. One
way I though about doing it is

def logins
EventList.new @events.select{|e| e.action == :login}
end

class EventList
def initialize data
@data = data
end
def [] date
@data.select{|e| e.date == date}
end
end

logins[Date.today] # => all logins today from @events

I guess some people might prefer to write a method like
get_logins(date), but I like this syntax. It seems reasonable to also
define []= in EventList to update the original @events. What I'd like
to know is if there's another way to solve this problem, or if there
are any simple optimizations (maybe only keep one instance of
EventList and update its contents with each call to #events).

def logins
@_logins ||= Proc.new do |date|
@events.select{|e| e.action == :login and e.date == date}
end
end

However, I feel you are limiting yourself. Try something like this
instead:

def logins
@_logins ||= (
l = @events.select{|e| e.action == :login}
def l.by_date(date)
select{|e| e.date == date}
end
l
)
end

Then you can use:

logins.by_date(date)

If needed, you could change #logins to lazy evaluate too.

T.


.



Relevant Pages

  • Re: Behaviour of Enumerables reject vs. select mixed into Hash
    ... Yes, but making a special case of Hash, as opposed to other ... more harmful to duck-typing than either not returning an array. ... def add_from_e_method ... self << elem ...
    (comp.lang.ruby)
  • Re: Array of Hashes in an array of hashes - Complicated!
    ... because of the repeating fields within the data. ... array of hashes at my top level, i have an array of objects that have ... hash of arrays....... ... def initialize() ...
    (comp.lang.ruby)
  • Re: Using a class namespace for subclasses
    ... Hash, however, has got to be one of the top candidates, along with Array, for sticking stuff into. ... that reminds me, what i did for arrayfields, which adds a bunch of methods to Array __instances__ is something like ... def foo ...
    (comp.lang.ruby)
  • Re: Mode method for Array
    ... the array as the keys, and the number of times the keys occur as the ... Then I create a new hash out of that first hash with the ... def hash_of_frequency ...
    (comp.lang.ruby)
  • Re: Slightly OT: Wanted -- the most rubyish way to do this...
    ... To this index it is easy to add an offset. ... TWO objects -- the hash AND the array? ... I recommend using a Hash internally in the object. ... def initialize ...
    (comp.lang.ruby)