Ruby lambda 接 block 参数的问题

logchi · 2014年03月07日 · 最后由 logchi 回复于 2014年03月07日 · 1935 次阅读

接着我昨天的问题,下面是我在实际项目中的代码,不确定这样写行不行。

def lines_array(*coordinate)
  count = LineInfo.where(player: self.to_pointer).count
  if count == 0
    return []
  else
    lines = LineInfo.where(player: self.to_pointer).execute
    first = true
    path = []
    construct_path = ->(*coordinate, &operation) {
      if lines.empty?
        return path
      elsif lines.size == 1
        operation.call lines
        return path
      else
        target_index = 0
        if first
          target_index = -1 
          first = false
        end
        base_x, base_y = transform_coordinate coordinate
        lines.sort_by! do |line|
          x, y = transform_coordinate( line.pointArray[-1].split(':') )
          (base_x - x)**2 + (base_y - y)**2
        end
        the_line = operation.call lines
        x, y = the_line.pointArray[target_index].split ':'
        construct_path.call(x, y) do |lines|
          the_line = lines.shift
          path << {
            color: the_line.color,
            style: the_line.style,
            pointArray: converse_coordinates(the_line.pointArray)
          }
          the_line
        end
      end
    }
    construct_path.call(*coordinate) do |lines|
      the_line = lines.shift
      path << {
        color: the_line.color,
        style: the_line.style,
        pointArray: converse_coordinates(the_line.pointArray)
      }
      the_line
    end
  end
end

def transform_coordinate(coordinate)
  [coordinate[0].to_i, coordinate[1].to_i]
end

def converse_coordinates(ary)
  if ary.nil?
    []
  else
    ary.map do |coordinate|
      x, y = coordinate.split ':'
      "{#{x}, #{y}}"
    end
  end
end

最后的调用像这个样子

player.lines_array( '123', '456' )

其中 line 的 pointArray 是一个 [ "123:456", "789:123" , ... ] 这样的坐标字串数组。 coordinate 是一个点的坐标 x ,y 字串数组,像这个样子 [ '123', '456' ]

对于含有 block 参数的 lambda,递归要像下面这样写吗?

base = 10
lambda_x = ->(&block_x) {
  if base == 0
    return
  else
    base -= 1
    puts 'some operations...'
    block_x.call
    lambda_x.call do
      puts "I'm in block_x"
    end
  end
}

lambda_x.call do
  puts "I'm in block_x"
end

#1 楼 @logchi 这么写没什么问题啊

你实际项目里的代码太过于 Ugly 了。。看不下去。。

#2 楼 @iBachue 我也是这样觉得的,正在改善 ^^

需要 登录 后方可回复, 如果你还没有账号请 注册新账号