2009/01/31

Enumerator

新刊書「プログラミング言語 Ruby」をよみつつ..
p140.
Enumerator の練習。

e = "100"
# => "100"
e.class
# => String
e.methods

e = "100".each_char
# => <Enumerator:0x1f44c4>
e.class
# => Enumerator
e.methods

e.to_a
#["1", "0", "0"]
e.entries
#["1", "0", "0"]
e.grep("0")
#["0", "0"]
e.find("1"){|x| p x}
# => "1"
e.each.find{|x| x == "1"}
# => "1"
e.count
# => 3

a = "aaa"
b = a.codepoints
b.class
# => Enumerator
a.class
# => String
"a".codepoints.class
# => Enumerator

a.methods

a = "aaa".chars.entries
# => ["a", "a", "a"]
a = "abc".codepoints.entries
# => [97, 98, 99]
a = "aaa".bytes.to_a
# => [97, 97, 97]

"a" は String だけど .chars や、.each_char .codepoints などすると,とたんに Enumerator クラスのメソッドが使えるようになるのですね。

つくってみたメソッド...
# マルチバイトが含まれているか?

# coding: utf-8
def multibyte?(str)
  n = str.codepoints.entries.find{|m| m > 128}
end

str = "るびー"
puts "multiByte" if multibyte?(str)
puts "none multiByte" unless multibyte?(str)


ついでにかきなおしたやつ(readbook関連)
# 数字にカンマをあたえる
# Ruby Way にのっていたのより3倍はながい

def comma(str)
  str = str.to_s
  return nil if /[^0-9]/.match(str)
  s = str.size
  res, k = [], (s - 4) % 3
  ary = str.chars.to_a
  ary.each_index{|x|
    res << ary[x]
    (x == k and x + 1 < s) ? (k, res = k + 3, res << ",") : k
  }
  return "\u{A5} " + res.join('')
end

str = "111321"
comma(str)
# =>
# "¥ 111,321"


三項演算子はたのしい。

+++ 追記 +++
2009-02-01.

String クラスには ascii_only? があった。

"a".ascii_only?
=> true
"abcあ".ascii_only?
=>false

multibyte? メソッドは不要であった...

--imported_from
http://www.midore.net/daybook/2009/01/1233333360.html

0 件のコメント: