F1e3ab214a976a39cfd713bc93deb10f

Everything else in my lib is pretty elegant, however this part bugs me. I cant use #find since I need the value the method send(token) returns, not the token name itself. Is there a baked in iterator that I forgot about that would work good here?

def get_token
      self.class.precedence.each do |token|
        if val = send(token)
          return val
        end
      end
      error 'syntax error'
    end

Refactorings

No refactoring yet !

C1f7bc8064161e7408ef62d97bb636ac

Mortice

November 13, 2009, November 13, 2009 17:21, permalink

No rating. Login to rate!

There's some discussion about a proposed iterator to do just this kind of thing on ruby-talk at the moment. I guess your code would end up looking something like this with the new iterator added.

#find_yield definition by Intransition on ruby-talk mailing list
module Enumerable
 def find_yield(fallback = nil)
   each do |member|
     result = yield(member)
     return result if result
   end
   fallback
 end
end


self.class.precedence.find_yield {|token| send(token)} || error 'syntax error'
D85d44a0eca045f40e5a31449277c26c

Ben Marini

November 13, 2009, November 13, 2009 21:31, permalink

No rating. Login to rate!

Sounds like something you implement nicely in Ruby 1.9 using a lazy enumerator:
http://www.michaelharrison.ws/weblog/?p=163

F1e3ab214a976a39cfd713bc93deb10f

Tj Holowaychuk

November 13, 2009, November 13, 2009 22:27, permalink

No rating. Login to rate!

ya an enumerator would work fine, this is 1.8.x tho

F4192eeb4b26e96deab8b5c68926105d

Muke Tever

November 14, 2009, November 14, 2009 17:07, permalink

1 rating. Login to rate!

I think you *could* use find, if you really wanted to; just move 'val' outside of the find block's scope.

def get_token
  val = nil
  self.class.precedence.find {|token| val = send(token) }
  val || error('syntax error')
end

# with val in the method signature you could, say, 
# specify a fallback value instead of an error sometimes
# (if that makes sense in this context; I don't know)
def get_token(val=nil)
  self.class.precedence.find {|token| if x = send(token) then val = x end } 
  val || error('syntax error')
end
B397b498cc02503a2d86c86176f7fd3e

Magnus Holm

November 16, 2009, November 16, 2009 22:13, permalink

2 ratings. Login to rate!
def get_token
  self.class.precedence.each { |token| return send(token) || next }
  error('syntax error')
end

Your refactoring





Format Copy from initial code

or Cancel