English 中文(简体)
优化利用鲁比拉的“Boundarize”新方法
原标题:Optimizing this "Boundarize" method for Numerics in Ruby

I m 采用我称之为“Boundarize”的方法,因为缺乏更好的名称;我确信,实际上有这方面的真实姓名。 但是,其基本目的是重新确定一个边界内的特定点。

这就是说,“打捞”是边界周围的一个点;如果面积为0到100,如果点为:

-1.boundarize(0,100)        # => 99 

(从最高点到“最高点”的点数太远。)

102.boundarize(0,100)       # => 2

它是执行的一个非常简单的职能;如果数量低于最低水平,则在边界上加(最大)。 如果该数字高于上限,则简单地将(最大)推向边界。

我还需要说明的是,在有些情况下,我不想将最低范围包括在内,而且我不想将最高范围纳入其中。 这一点作为论据加以说明。

然而,我担心,我目前的执行是可怕、可怕、严重效率低下的。 由于每次在屏幕上移动,必须重新开张,这是我申请的瓶颈。 没有人有什么想法?

module Boundarizer

  def boundarize min=0,max=1,allow_min=true,allow_max=false 

    raise "Improper boundaries #{min}/#{max}" if min >= max
    raise "Cannot have two closed endpoints" if not (allow_min or allow_max)

    new_num = self

    if allow_min
      while new_num < min
        new_num += (max-min)
      end
    else
      while new_num <= min
        new_num += (max-min)
      end
    end

    if allow_max
      while new_num > max
        new_num -= (max-min)
      end
    else
      while new_num >= max
        new_num -= (max-min)
      end
    end

    return new_num

  end

end

class Numeric
  include Boundarizer
end

0.boundarize(10,50)             # => 40
10.boundarize(0,10)             # => 0     (the maximum is by default not allowed)
0.boundarize(0,20,false)        # => 20    (the minimum is not allowed)
最佳回答

看起来像大家一样,你所需要的是组合式(占运营商的%),同时还要进行一些额外的检查,以便处理肥胖症和允许最大程度:

irb(main):002:0> -1 % 100
=> 99
irb(main):003:0> -101 % 100
=> 99
irb(main):004:0> 102 % 100
=> 2
问题回答

http://en.wikipedia.org/wiki/Modulo_operation”rel=“nofollow noretinger” 。

鲁比为经营者提供了%。





相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签