Array#&で集合の積
配列同士の & をとると、集合の積になります。refe "Array#&" 参照。
以下では2の倍数twosと3の倍数threesの積をとって、6の倍数を得ています。
twos = [] threes = [] (0..10).each do |k| twos << 2 * k threes << 3 * k end p twos #=> [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20] p threes #=> [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30] p twos & threes #=> [0, 6, 12, 18]
Array.[]というメソッド
ふと気がついた。Array.[]もメソッドなんだから、methodメソッドでメソッドオブジェクトにできるよね。
m = Array.method(:[]) a = m.call('Red', 'Green', 'Blue') p a #=> ["Red", "Green", "Blue"]
Array.newもね。
m = Array.method(:new) a = m.call(5, 'Rubyco') p a #=> ["Rubyco", "Rubyco", "Rubyco", "Rubyco", "Rubyco"]
Arrayでの負の添字
Rubyでは、負の添字は配列末尾から逆方向にたどった要素に対応します。-1が末尾の要素、-2は末尾から2番目、-3は末尾から3番目。
ar = ['Red', 'Green', 'Blue'] p ar[-4] #=> nil p ar[-3] #=> "Red" p ar[-2] #=> "Green" p ar[-1] #=> "Blue" p ar[ 0] #=> "Red" p ar[ 1] #=> "Green" p ar[ 2] #=> "Blue" p ar[ 3] #=> nil
String#eachで区切り文字列指定
String#eachで区切り文字列を指定すると、その区切り文字で区切ります。区切り文字は残ったままです。
s = "Alice,Bobby,Chris,David" s.each(",") do |w| puts w end
実行結果です。
Alice, Bobby, Chris, David
methodで得たメソッドオブジェクトはselfを知っている
methodメソッドを使うと、メソッドオブジェクトを得ることができます。得たオブジェクトは元のselfを知っています。
class Rubyco def initialize(you) @you = you end def hello puts "Hello, #{@you}!" end attr_accessor :you end r = Rubyco.new("Alice") r.hello #=> Hello, Alice! m = r.method(:hello) m.call #=> Hello, Alice! r.you = "Bobby" m.call #=> Hello, Bobby!
このように、途中で@youの値を"Bobby"に変えると、m.callの結果もそれに応じて変化します。mが保持しているメソッドオブジェクトが元のRubycoオブジェクトを持っているからです。
methodメソッド
methodメソッドを使うと、メソッドオブジェクトを得ることができます。得るメソッドは名前で指定します。
p 1.method(:nil?) #=> #<Method: Fixnum(Kernel)#nil?> p nil.method(:nil?) #=> #<Method: NilClass#nil?>
得たメソッドのアリティ、文字列表現、呼び出しは以下の通り。
p nil.method(:nil?).arity #=> 0 p nil.method(:nil?).inspect #=> "#<Method: NilClass#nil?>" p nil.method(:nil?).call #=> true
to_procでProcにしてからcallすることもできる。
p nil.method(:nil?).to_proc.call #=> true
もう何がなにやら。
p nil.method(:method).call(:nil?).to_proc.call #=> true p nil.method(:method).to_proc.call(:method).to_proc.call(:nil?).to_proc.call #=> true
nilで使えるメソッド名一覧
methodsメソッドで、そのオブジェクトのメソッド名のリストが得られます。ということは、次のようにすると、nilのメソッド名のリストが得られます。
puts nil.methods.sort
実行結果です。
& == === =~ ^ __id__ __send__ class clone display dup eql? equal? extend freeze frozen? hash id inspect instance_eval instance_of? instance_variable_get instance_variable_set instance_variables is_a? kind_of? method methods nil? object_id private_methods protected_methods public_methods respond_to? send singleton_methods taint tainted? to_a to_f to_i to_s type untaint |
む、cloneメソッドですと?
p nil.clone #=> in `clone': can't clone NilClass (TypeError)
nilはcloneできません。cloneしてしまうと、同一性がおかしくなるからでしょう。