c4se記:さっちゃんですよ☆

.。oO(さっちゃんですよヾ(〃l _ l)ノ゙☆)

.。oO(此のblogは、主に音樂考察Programming に分類されますよ。ヾ(〃l _ l)ノ゙♬♪♡)

音樂は SoundCloud に公開中です。

考察は現在は主に Scrapbox で公表中です。

Programming は GitHub で開發中です。

Range 'a' .. String::INFINITY (Ruby)

追記20131003
私のはまともにtestしてゐないクソ仕様なので、merborneさまのに追隨してください。
cf. RubyのStringにもInfinityを!- 反省回 - http://melborne.github.io/2013/10/01/string-infinity-regret/
此のの間のDart風のautomatic field initializationをRubyでは、 @ さまに追加攻撃を受け、issueにも成った。
cf. RubyistたちのDRY症候群との戦い http://melborne.github.io/2013/09/27/auto-attr-set-in-ruby/
cf. def initialize @a, @b; end · Issue #3 · ne-sachirou/AutoAttrInit.rb https://github.com/ne-sachirou/AutoAttrInit.rb/issues/3
お返しをしておこうと思ふ。此の「お返し」は、言葉の洞の意味での「お返し」ととって貰っても構わない。

Rubyの文字列だってえにゅめらぶるしたい!

cf. Rubyの文字列だってえにゅめらぶるしたい! http://melborne.github.io/2013/09/26/be-string-enumerable/

単純に出来そうだと思ったのでやった。
('a' .. String::INFINITY).lazy.take 10000とか出来る丈。

# coding=utf-8

# Rubyの文字列だってえにゅめらぶるしたい!
# http://melborne.github.io/2013/09/26/be-string-enumerable/
class StringInfinity < String; end
String::INFINITY = StringInfinity.new

# Class: Range (Ruby 2.0.0)
# http://ruby-doc.org/core-2.0.0/Range.html#method-i-each
# rubinius/kernel/common/range.rb at master ・ rubinius/rubinius
# https://github.com/rubinius/rubinius/blob/master/kernel/common/range.rb
class Range
  def each_with_string_infinity
    return to_enum unless block_given?
    if last == String::INFINITY
      current = first
      while true
        yield current
        current = current.succ
      end
    else
      each_without_string_infinity{|v| yield v }
    end
  end
  alias_method :each_without_string_infinity, :each
  alias_method :each, :each_with_string_infinity
  private :each_with_string_infinity

  unless method_defined? :size
    define_method :size do
      return Float::INFINITY if last == Float::INFINITY
      to_a.length
    end
  end
  def size_with_string_infinity
    return Float::INFINITY if last == String::INFINITY
    size_without_string_infinity
  end
  alias_method :size_without_string_infinity, :size
  alias_method :size, :size_with_string_infinity
  private :size_with_string_infinity
end

$DEBUG = true

# http://c4se.hatenablog.com/entry/2013/08/15/022137
def unittest test_name, &proc
  if $DEBUG
    include Test::Unit::Assertions
    proc.call
    puts "#{test_name} ok."
  end
end
if $DEBUG
  require 'test/unit/assertions'
end

 unittest 'String::INFINITY has no side effect' do
   range = 1 .. Float::INFINITY
   assert_equal Float::INFINITY, range.size
   assert_equal [1, 2, 3], range.take(3)

   range = 'a' .. 'zz'
   assert_equal 702, range.size
   assert_equal ['a', 'b', 'c'], range.take(3)
 end

 unittest 'String::INFINITY works' do
   range = 'zzz' .. String::INFINITY
   assert_equal Float::INFINITY, range.size
   assert_equal ['zzz', 'aaaa', 'aaab'], range.take(3)
 end

String#succはASCIIしか巡らない。


今見たらmerborneさまもやってゐた。
cf. RubyのStringにもInfinityを! http://melborne.github.io/2013/09/30/string-infinity-discovered/