たのしいRuby 第3章,第4章 コマンドを作ろう

なんか、ふつうのLinuxプログラミングと同じ流れだ・・・

catを作ろう

catを作ってみる。複数ファイル対応に改造した。

cat.rb
#!/usr/bin/ruby

ARGV.each do |name|
  file = open name
  while text = file.gets do
    puts text
  end
  file.close
end

実行〜

% ./cat.rb *
#!/usr/bin/ruby

ARGV.each do |name|
...(略

だが・・・

% ./cat.rb hoge.rb
./cat.rb:4:in `initialize': No such file or directory - hoge.rb (Errno::ENOENT)
        from ./cat.rb:4:in `open'
        from ./cat.rb:4
        from ./cat.rb:3:in `each'
        from ./cat.rb:3

ファイル名が無いとエラーがでる。エラー処理はもうちょっと進んでからやろうと思う。

grepを作ろう

本物にあわせてみた(適当に

#!/usr/bin/ruby

if ARGV.size < 2
  puts "Usage: grep.rb PATTERN [FILE]..."
  exit 1
end

pattern = Regexp.new(ARGV.shift)

ARGV.each do |name|
  file = open name
  while text = file.gets do
    if text =~ pattern
      print name + ":" + text
    end
  end
  file.close
end

実行〜

% ./grep.rb 'while.*do' *
cat.rb:  while text = file.gets do
grep.rb:  while text = file.gets do
% grep 'while.*do' *
cat.rb:  while text = file.gets do
grep.rb:  while text = file.gets do
% ./grep.rb
Usage: grep.rb PATTERN [FILE]...
% grep
Usage: grep [OPTION]... PATTERN [FILE]...
Try `grep --help' for more information.

本物と遜色無い!!(オプションとか無いけどね・・・

コラムのワンライナがすげぇ

カッコいい。

% cat * | tr ' ' '\n' | sort | uniq -c | sort -rn | head -5
     45
      7 end
      5 text
      5 do
      5 =

楽しくなってきたぞぉ〜

4章

irbで確認した。

irb(main):018:0> str1.equal?(str2)
=> true

何故「is_」ではなく、「?」を使うのかイマイチ不明。

謎だらけの言語だ。たぶん普通じゃない。

朝飯食いながらRubyのソースを眺めてみた

ruby.hに重要な構造体があった。

  struct
    RBasic
    RObject
    RClass
    RFloat
    RString
    RArray
    RRegexp
    RHash
    RFile
    RData
    RStruct
    RBignu

たぶんRubyの根幹だと思う。st.hも重要そう。

tanaka既に、Rubyハッカー(まだ早すぎ

驚いた

Rubyソースコード完全解説でも、重要ポイントとして取り上げられてた!!

tanaka。目の付けどころがいいな(by 青木さん

Rubyの勉強を進めたい。