1.2 オープンクラス
def to_alphanumeric()
s.gsub /[^wa]/,””
end
require ‘test/unit’
class ToAlphanumericTess < Test::Unit::TestCase
def test_strips_non_alpanumeric_characters
assert_equal ‘3 the Magic Number’,
to_alphanumeric(‘#3, the *Magic, Number*?’)
end
end
12年11月13日火曜日
class String
def to_alphanumeric
gsub /[^ws]/,’’
end
end
class StringExtensionsTest < Test::Unit::TestCase
def test_strips_non_alphanumeric_characters
assert_equal ‘3 the Magic Number’,
‘#3, the *Magic, Number*?’.to_alphanumeric
end
end
12年11月13日火曜日
1.2.1 クラス定義の中身
クラスを定義するコードと
その他のコードの違いはない
3.times do
実行
class C
puts “Hello” Hello
end Hello
end Hello
これは同じクラスを3回定義したわけではない
12年11月13日火曜日
26.
class D obj = D.new
def x; ‘x’;end obj.x #=> ‘x’
end obj.y #=> ‘y’
class D
def y; ’y’; end
end
class Dを書いた時はまだ、クラスは存在していない。
Rubyがクラス定義の中に入った時に、初めて定義をする
1回目ではxメソッドを定義して2回目の際は既にクラス
があるので、class Dを再オープンしてyメソッドを追加す
る。
12年11月13日火曜日
1.2.2オープンクラスの問題点
def replace(array, from ,to)
array.each_with_index do |e,i|
array[i] = to if e == from
end
end
def test_replace
book_topics = [‘html’,‘java’,‘css’]
replace(book_topics,‘java’,‘ruby’)
expected = [‘html’,‘ruby’,‘css’]
assert_equal expected , book_topics
end
12年11月13日火曜日
30.
class Array
def replace(from,to)
each_with_index do |e,i|
self[i] = to if e == from
end
end
end
def test_replace
book_topics = [‘html’,‘java’,‘css’]
replace(book_topics,‘java’,‘ruby’)
expected = [‘html’,‘ruby’,‘css’]
assert_equal expected , book_topics
end
12年11月13日火曜日
Object Module
class
obj1 superclass superclass
Class
MyClass new()
...
obj2
class class
・オブジェクトと同じように、クラスも参照を使って保持する
・obj1とMyClassはどちらも参照であり違うのは
・obj1は変数
・MyClassは定数である
12年11月13日火曜日
1.4 クイズ引かれていない線
superclass
obj1
class Object Module
class
superclass
class superclass
obj2
Class
MyClass new()
...
obj3 class
@x=10 class class
12年11月13日火曜日