代码之家  ›  专栏  ›  技术社区  ›  philosodad

用更好的解决方案替换“eval”

  •  0
  • philosodad  · 技术社区  · 15 年前

    add_by 方法。

    一些解释:每 节点 :x , :y :neighbors . 是表示平面坐标的整数, :邻居 是数组,节点存储在 @nodes k 在里面 ,在一定距离内的节点 d @neighbors 数组 .

     def set_neighbors d
        def add_by dim, d
          dict = {}
          @nodes.each{|k| dict[k] = []}
          @nodes.each_index do |k|
            up = k+1
            down = k-1
            while up < @nodes.length and ((eval '@nodes[k].'+ dim) - (eval '@nodes[up].'+dim)).abs <= d
              dict[@nodes[k]].push(@nodes[up])
              up += 1
            end
            while down >= 0 and ((eval '@nodes[k].'+ dim) - (eval '@nodes[down].'+dim)).abs <= d
              dict[@nodes[k]].push(@nodes[down])
              down -= 1
            end
          end
          return dict
        end
        @nodes.sort_by{|k| k.x}
        exis = add_by('x', d)
        whys = add_by('y', d)
        @nodes.each do |k|
          neighbors = exis[k]&whys[k]
          k.neighbors = neighbors.select{|j| planar_distance(j,k) <= d}
        end
      end
    

    添加方式 例行程序 x y 或者使用eval?

    2 回复  |  直到 15 年前
        1
  •  3
  •   Jakub Hampl    15 年前

    你可以使用 @nodes[k].send dim.to_sym .

    def set_neighbors d
      @nodes.each do |node|
        node.neighbors = @nodes.select do |n| 
          (node.x - n.x).abs <= d && 
          (node.x - n.x).abs <= d &&
          planar_distance(n,node) <= d
        end - node
      end
    end
    
        2
  •  2
  •   Mark Thomas    15 年前

    怎么会 做吗?我会用 Neo4J source ). 如果您关心性能,这是为图形距离计算优化的。而且这个API非常好。

    也就是说,你真的不需要评估。可以通过使用 send @nodes[k].send(dim) , @nodes[up].send(dim) 等等。