From: Yoshinori Toki Date: 1999-06-25T17:53:00+09:00 Subject: [ruby-list:15111] attr makes a strange name method 土岐です。 Module::attr を使うと a?=, b!=, c== のような変な名前のメソッドが定義で きてしまいます。さらに c== はスクリプトから普通に呼べてしまうみたいで す。a?=, b!= は普通に呼び出そうとするとエラーになるんですが、 Object#send と String#intern を使えば呼べてしまいます。あと代入後に作 られるインスタンス変数の名前に ?, !, = が付いてしまってます。 シンボル値ではなく文字列でメソッド名を指定すれば、途中で空白が入ったり カンマやピリオドで区切ったりしたような名前のメソッドでも定義できてしま うみたいです。 Ruby のバージョンは ruby 1.3.4 (1999-06-24) [i386-freebsd3.1] です。 別に実害は無いんですが、なんとなく気持悪かったので報告しました。 (ここからテスト用スクリプト) class AttrTest attr :a?, true attr :b!, true attr :c=, true attr "Just another Ruby hacker,", true end DEBUG = binding def debug(expr) begin puts "EXPR:#{expr}" eval(expr, DEBUG) rescue puts $! end end debug %q[ attr = AttrTest::new ] debug %q[ p attr.methods.grep(/^#{Regexp::quote("a?")}/) ] debug %q[ p attr.methods.grep(/^#{Regexp::quote("b!")}/) ] debug %q[ p attr.methods.grep(/^#{Regexp::quote("c=")}/) ] debug %q[ attr.a? = "a" ] debug %q[ attr.b! = "b" ] debug %q[ attr.c= = "c" ] debug %q[ p attr.instance_variables ] debug %q[ attr.send("a?=".intern, "a") ] debug %q[ attr.send("b!=".intern, "b") ] debug %q[ attr.send("c==".intern, "c") ] debug %q[ p attr.instance_variables ] debug %q[ p attr.methods.grep(/^Just another Ruby hacker,/) ] debug %q[ attr.send("Just another Ruby hacker,=".intern, true) ] debug %q[ p attr.send("Just another Ruby hacker,".intern) ] debug %q[ p attr.instance_variables ] (ここから実行結果) EXPR: attr = AttrTest::new EXPR: p attr.methods.grep(/^#{Regexp::quote("a?")}/) ["a?", "a?="] EXPR: p attr.methods.grep(/^#{Regexp::quote("b!")}/) ["b!", "b!="] EXPR: p attr.methods.grep(/^#{Regexp::quote("c=")}/) ["c=="] EXPR: attr.a? = "a" (eval):1: compile error (eval):1: parse error attr.a? = "a" ^ EXPR: attr.b! = "b" (eval):1: compile error (eval):1: parse error attr.b! = "b" ^ EXPR: attr.c= = "c" EXPR: p attr.instance_variables ["@c="] EXPR: attr.send("a?=".intern, "a") EXPR: attr.send("b!=".intern, "b") EXPR: attr.send("c==".intern, "c") EXPR: p attr.instance_variables ["@c=", "@b!", "@a?"] EXPR: p attr.methods.grep(/^Just another Ruby hacker,/) ["Just another Ruby hacker,=", "Just another Ruby hacker,"] EXPR: attr.send("Just another Ruby hacker,=".intern, true) EXPR: p attr.send("Just another Ruby hacker,".intern) true EXPR: p attr.instance_variables ["@c=", "@b!", "@Just another Ruby hacker,", "@a?"] ---------------------------------------------------------------------------- 土岐 仁謙 神戸大学物理高エネ研 M2 URL: http://www3.phys.sci.kobe-u.ac.jp/~toki/index.html PGP fingerprint = D0 A8 90 AB 73 F8 34 FE CE CA DB BF 01 30 C0 35