Tbpgr Blog

Organization Development Engineer tbpgr(てぃーびー) のブログ

Ruby | Range | step

概要

Range#step(s = 1) {|item| ... } -> self
Range#step(s = 1) -> Enumerator

詳細

範囲内の要素を s おきに繰り返却

サンプルコード
require 'tbpgr_utils'

class Hoge
  attr_accessor :count

  def initialize(count)
    @count = count
  end

  def succ
    copy = self.dup
    copy.count += 1
    copy
  end

  def <=>(other)
    @count <=> other.count
  end
end

hoge_min = Hoge.new(3)
hoge_max = Hoge.new(20)

bulk_puts_eval binding, <<-EOS
(2..10).step(2)
(2..10).step(2).to_a
(hoge_min..hoge_max).step(3).to_a
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

(2..10).step(2)                   # => #<Enumerator: 2..10:step(2)>
(2..10).step(2).to_a              # => [2, 4, 6, 8, 10]
(hoge_min..hoge_max).step(3).to_a # => [#<Hoge:0x00000600c40670 @count=3>, #<Hoge:0x00000600c37728 @count=6>, #<Hoge:0x00000600c37688 @count=9>, #<Hoge:0x00000600c37610 @count=12>, #<Hoge:0x00000600c37570 @count=15>, #<Hoge:0x00000600c374d0 @count=18>]