开发者

Overriding default range output

Right now the code below produces the output below it, but how would I override the default output to a more logical one for my given situation. I understand that I could just append the string "Hz" after the range but I want to incorporate this into a module which can be开发者_如何学Python included to the Range class when needed or for use with refinements.

Code:

("20Hz"..."40Hz").each { |hz| p hz }     

Output:

"20Hz"
"20Ia"
"20Ib"
...etc

Wanted output:

"20Hz"
"21Hz"
"22Hz"
...etc


This is absolutely a bad idea, but just for the sake of experimenting:

class String
  alias_method :succ_orig, :succ

  def succ
    self.gsub(/\d+/, &:succ_orig)
  end
end

p ("20Hz".."40Hz").to_a
#=> ["20Hz", "21Hz", "22Hz", "23Hz", "24Hz", "25Hz", "26Hz", "27Hz", "28Hz", "29Hz", "30Hz", "31Hz", "32Hz", "33Hz", "34Hz", "35Hz", "36Hz", "37Hz", "38Hz", "39Hz", "40Hz"]

As you can see, it is not the Range class that should be altered, but String#succ method.

But in real project, you better create a class for your Hertz-strings and define its succ method appropriately.


I think its quite simple.

  ("20"..."40").each { |hz| p hz + 'Hz'}


I would recommend creating your own function or class for this rather that changing the way in which Ruby ranges behave. There is probably a lot of other code that depends on ranges working in a specific way, and changing the range definition would result in that code breaking. You might want to aim for something like this:

HzRange.new("20Hz", "40Hz").each{ |hz| p hz }

The creation of the HzRange class is up to you, but you should probably delegate to the Array or Range object so that you can inherit some default behavior like Enumerable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜