たのしいRuby 第5版

図書館にあった たのしいRuby 第5版 を読む。
手元の本は第2版で1.8が対象だったのだが、1.9以降のStringの仕様変更の理解がずっと浅いように感じているので、第3部を中心に落ち穂拾い的にあちこち読んで見る。
以下気になった点のメモ。1.8でもあったものかどうかは調べていないが、知らないことが多い。

第12章 数値(Numeric) クラス

これまで有理数複素数を使う機会はなく、スルーしていた部分。

有理数複素数
r = Rational(2, 3)
p r.to_f
p [r.numerator, r.denominator]
r2 = 1.3r
p r2
c1 = Complex(1, 2)
c2 = 3i
c = c1 + c2
p c
p [c.real, c.imaginary]

数値の型変換 Numeric#round

四捨五入する位置を指定する引数がある

p 12.34.round(1)
p 12.34.round(-1)
p 12.34.round

第13章 配列(Array) クラス

Array.new あれこれ。
Array.new       # => []
Array.new(3)    # => [nil, nil, nil]
Array.new(3, 0) # => [0, 0, 0]
Array.new(3, [0, 0, 0])    # => 各要素は同じオブジェクトを指す
Array.new(3) { [0, 0, 0] } # => 各要素は別のオブジェクト
Array.new(3) { |i| i * 2 } # => [0, 2, 4]
Array#values_at
a = %w(a b c d e)
a.values_at(0, 2, 4) # => ["a", "c", "e"]

第14章 文字列(String) クラス

ヒアドキュメント
def hear_test
  s1 = <<EOS
    string
EOS
  s2 = <<-EOS
    string
  EOS
  s3 = <<~EOS
    string
  EOS
  p s1, s2, s3
end

hear_test

<<~ は 2.3.0から追加とのこと

全角英数を半角へ、かつ半角カナを全角カナへ

仕事でよく出てくるパターン。NKFでうまくいく。

s = "これがコレガコレガABC123 abc123"
p s                   # => "これがコレガコレガABC123 abc123"
p NKF.nkf('-wZ1X', s) # => "これがコレガコレガABC123 abc123" 

第15章 ハッシュ(Hash) クラス

Hash#store, Hash#fetch
h = Hash.new('')
h[:p]                  # => ''
h.fetch(:p)            # => KeyError
h.fetch(:p, '(undef)') # => '(undef)'
デフォルト値
  • Hash.new(value)
  • Hash.new { |hash, key| }
  • Hash#fetch(key, value)

Hash.new にブロックを渡す例

h1 = Hash.new('')
h2 = Hash.new do |hash, key|
  hash[key] = key.upcase
end

第16章 正規表現(Regexp) クラス

Unicode文字プロパティを使った文字クラス指定
/\p{Hiragana}/
/\p{Katakana}/
/\p{Han}/

使うことはないだろうと思う。

マッチ結果

$&, $1 ではなく Regexp.last_match を使うのも良さそう。
(Matchdata#to_a)

第17章 IOクラス

Fileオブジェクトを作成せずに読み書きする方法

File.read('in.txt', { encoding: 'utf-8' }) # option のハッシュも使えるようだ
File.write('out.txt', '漢字まじり', { encoding: 'utf-8' }) 

File.binread('in.bin')                     # バイナリファイルの場合
File.binwrite('out.bin', '漢字混じり')

他のコマンドとのやり取り

第18章 FileクラスとDirクラス

実際に使うときにヘルプを見れば良し。

第19章 エンコーディング(Encoding)クラス

1.8から1.9で変化の大きかったところ。
ファイルを扱う際は気をつけているが、ARGVのエンコーディング変換は時々忘れる。

第20章 TimeクラスとDateクラス

実際に使うときにヘルプを見れば良し。

第21章 Procクラス

Proc, ラムダ式について メタプログラミングRuby 第2版 を読むほうが良い。