Project

General

Profile

Feature #4787

Integer#each_modulo(n)

Added by mrkn (Kenta Murata) almost 9 years ago. Updated over 2 years ago.

Status:
Closed
Priority:
Normal
Target version:
-
[ruby-dev:43586]

Description

I suggest a new feature of Integer to enumerate by iterated Integer#modulo.
An example implementation in Ruby is the following code:

class Integer
  def each_modulo(n)
    raise ArgumentError, "argument must be an Integer" unless n.is_a? Integer
    raise ArgumentError, "argument must be larger than 1" if n <= 1
    return Enumerator.new(self, :each_modulo, n) unless block_given?
    q = self
    while q > 0
      q, r = q.divmod(n)
      yield(r)
    end
  end
end

p 133.each_modulo(3).to_a #=> [1, 2, 2, 1, 1]

The following code is an example use of the feature:

class Integer
  def each_thousand_separation
    each_modulo(1000)
  end

  def thousand_separated_string(sep=',')
    each_thousand_separation.map(&'%03d'.method(:%)).inject{|s, n| n + sep + s }
  end
end

p 100_000_000_200.thousand_separated_string #=> "100,000,000,200"

I make an implementation in C, and attach the patch for that.


Files

each_modulo.patch (3.91 KB) each_modulo.patch mrkn (Kenta Murata), 05/27/2011 01:18 PM

Related issues

Related to Ruby master - Feature #12116: `Fixnum#divmod`, `Bignum#divmod` with multiple argumentsOpenActions
Related to Ruby master - Feature #12447: Integer#digits for extracting digits of place-value notation in any baseClosedmatz (Yukihiro Matsumoto)Actions

Also available in: Atom PDF