2006-01-27から1日間の記事一覧

コロンとピリオド

Rubyco::Rosemaryは定数参照とみなされますが、Rubyco.Rosemaryはメソッド呼び出しとみなされます。 class Rubyco Rosemary = 123 def self.Rosemary return 456 end end p Rubyco::Rosemary # => 123 p Rubyco.Rosemary # => 456 p Rubyco::Rosemary() # =>…

super

Rubyのsuperは元メソッドを呼び出しますが、括弧と引数がないときには元メソッドの引数がそのまま渡されます。 class Parent def rubyco(x = 123, y = 456) print "Parent: rubyco(#{x}, #{y})\n" end end class Child < Parent def rubyco(x, y) if x == 0 …

配列の参照・代入

Rubyでは、配列の参照はというメソッド、代入は=というメソッドになります。 class RubycoArray def initialize(size) @arr = [] @size = size end def []=(index, value) if index < 0 or @size <= index raise "index is out of bounds" else @arr[index] …

クラス名は大文字

Rubyのクラス名は大文字で始めます(定数になります)。 class rubyco # class/module name must be CONSTANT end

eval

evalで評価できます。 eval <<"EOD" class Rubyco def self.hello print "Hello!\n" end end EOD Rubyco.hello

self.new

クラスメソッドnewを(superを呼ばずに)オーバーライドしてしまうと、newできなくなります。 class Rubyco def self.new print "new is overridden.\n" end def hello print "Hello!\n" end end a = Rubyco.new p a # => nil a.hello # => undefined method `…

self.newのすげかえ

クラスメソッドnewの最後にsuperじゃなく、他のオブジェクトを作ってみました。動きますね。 class Rosemary def hello print "Hello, Rosemary!\n" end end class Rubyco def self.new print "new is overridden.\n" Rosemary.new end def hello print "Hel…

モジュール

Rubyのmoduleはインスタンスを作れないクラスです。ということは、モジュールというのはネームスペースのようなものかしら。 module RubycoModule HELLO = 123 def self.hello print "Hello!\n" end end # a = RubycoModule.new # undefined method `new' fo…

モジュールとnew

でも、もちろん無理やりモジュールメソッドとしてnewを作ることはできますけれどね。 class RubycoClass def hello print "Hello!\n" end end module RubycoModule def self.new return RubycoClass.new end end a = RubycoModule.new a.hello # => Hello!

mixin

Rubyではincludeメソッドを使って、定義をインクルードできます。ということは、モジュールというのは抽象クラスのようなものかしら。 module RubycoModule def hello print "Hello!\n" end end class RubycoClass include RubycoModule end a = RubycoClass…

モジュールとmixin

Rubyのモジュールをincludeすると、実質的に多重継承ができます。 module DebugPrint def debug_print p self end end class Rubyco include DebugPrint def initialize(name) @name = name end end class Diamond include DebugPrint def initialize(x, y, …

Duck typing

Duck typingというのは、本当の型はクラスではなくオブジェクトが知っているという話。(if it walks like a duck, and talks like a duck, then it might as well be a duck) 参考: Duck typing - Wikipedia 参考: DuckTyping - rubygarden.org

String#each

String#eachメソッドは、普通は行単位で区切ります。 s = <<"EOD" This is the 1st line. This is the 2nd line. This is the 3rd line. EOD s.each { |line| p line }実行結果です。 "This is the 1st line.\n" "This is the 2nd line.\n" "This is the 3rd…

String#dump

String#dumpメソッドは文字をエスケープしてくれます。irbを使ってdumpとevalに戯れてみました。 irb(main):001:0> s = "print \"Ruby!\"\n" => "print \"Ruby!\"\n" irb(main):002:0> eval s Ruby!=> nil irb(main):003:0> p s "print \"Ruby!\"\n" => nil …