我目前正在審查一個使用元編程的 ruby 代碼庫。這意味著我不能總是用grep來查找方法的名稱,以找出它們的定義位置。
是否有辦法使用 ruby 反射來解決哪個模塊或類包含方法定義的問題?
例如,如果我正在審查類A,它有一長串的類和模塊包含在它的定義中。給定一個實體a = A.new(a),Ruby中是否有一些功能可以讓我用來檢索定義a.some_method的類/模塊?
uj5u.com熱心網友回復:
在Ruby中,你可以使用Method反射性代理物件來訪問代表一個方法的Object#method方法:
foo = [] 。
method = foo.method(: find)
#=> #<方法。Array(Enumerable)#find(*)>/span>
你可以使用Method#owner方法詢問方法的所有者:
method.owner
#=> Enumerable。
實際上不可能以編程方式區分屬性。屬性更多的是關于一個方法如何被使用,而不是它如何被定義。
您可以使用Method#parameters方法來獲取方法的引數串列,但這并不能讓您完全做到。沒有引數是屬性的一個必要條件,但不是充分條件。
例子:
class Foo
def bar; 42 end # attribute
def baz; puts 42 end # not an attribute
end
foo = Foo.new
foo.method(:bar).引數
#=> []
foo.method(:baz).引數
#=> []
你可以嘗試Method或UnboundMethod的每一個方法,你可以嘗試所有的元編程技巧,你根本無法找到任何可以區分bar是一個屬性和baz不是一個屬性的東西。
更糟糕的是,像Array#length這樣的方法,顯然是屬性,通常不被呼叫屬性。因此,即使有辦法以編程方式將屬性與其他無引數的方法區分開來,你仍然無法確定某個東西是否被認為是屬性。請注意,例如在Rubinius中,Array#length顯然甚至被實作為一個屬性,但它通常仍然不會被認為是一個屬性。
uj5u.com熱心網友回復:
不是標準的Ruby方式,但是pry gem有一個方便的ls命令,你可以將實體作為引數傳遞,它將顯示為該實體定義的每個方法以及這些定義所在的類。
例如,檢查一個整數的方法:
pry(main)(deve)> ls 1
可比的#methods: between?。
數值#methods:。
@ as_json coerce days exabyte gigabyte html_safe? in_milliseconds megabytes petabyte pretty_print real? second terabyte week
abs2 blank? conj duplicable? exabyte gigabytes i kilobyte minute petabytes pretty_print_cycle rect seconds terabytes weeks
angle byte conjugate encode_json fortnight hour imag kilobytes minutes phase quo rectangular singleton_method_added to_c
arg bytes day eql? fortnights hours imaginary megabyte nonzero? polar real remainder step to_formatted_s
RQRCode::CoreExtensions::Integer::Bitwise#methods: rszf。
整數#methods:
ceil denominator floor gcdlcm lcm months next ord ordinalize rationalize times to_d to_int to_r upto years
chr downto gcd integer? month multiple_of? numerator ordinal pred round to_bn to_i to_json_with_active_support_encoder truncate year
JSON::Ext::Generator::GeneratorMethods::Fixnum#methods: to_json。
Fixnum#methods:/span>
% * -@ < <== > >> ^ bit_length div even? inspect modulo paragraph sentence size to_csv to_f to_s words |?
& ** - / << <=> === >= [] abs dclone divmod fdiv magnitude odd? paragraphs sentences succ to_default_s to_msgpack word zero? ~
一個字串:
pry(main)(deve)> ls 'asdf'/span>
可比的#methods: < <= > >=之間?
JSON::Ext::Generator::GeneratorMethods::String#methods: to_json_raw to_json_raw_object to_json_without_active_support_encoder
字串#methods:。
% blueish codepoints each_line greenish issjis next pale rstrip! strip to_datetime tr_s
next!引數化 safe_constantize strip!to_f tr_s!
bullet_class_name colorized? encode gsub! kconv oct parse_csv scan strip_heredoc to_i trueish?
<< bytes concat encode! hash last on_black partition scanf sub to_json truncate
<=> bytesize constantize encode_json hex length on_blue pathmap scrub sub! to_json_with_active_support_encoder Truncate_words
== byteslice count encoding hide light_black on_cyan pluralize scrub! succ to_msgpack uncolorize
=== camelcase crypt end_with? html_safe light_blue on_green prepend setbyte succ! to_r underline
=~ camelize cyan ends_with? humanize light_cyan on_light_black purple shellescape sum to_s underscore
[] 大寫青色 eql? in_time_zone light_green on_light_blue purpleish shellsplit swap to_str unicode_normalize
[]=大寫!dasherize exclude? include? light_magenta on_light_cyan red singularize swapcase to_sym unicode_normalize!
act_like_string? casecmp deconstantize ext indent light_red on_light_green redish size swapcase! To_time unicode_normalized?
as_json center delete first indent! light_white on_light_magenta remove slice tableize toeuc unpack
ascii_only? chars delete! force_encoding index light_yellow on_light_red remove! slice! titlecase tojis upcase
at chomp demodulize foreign_key inquiry lines on_light_white replace split titleize tolocale upcase!
b chomp! downcase freeze insert ljust on_light_yellow reverse squeeze to tosjis upto
黑切下來!從檢查lstrip on_magenta反向!擠壓!to_builder toutf16 valid_encoding?
空白? chop! dump getbyte intern lstrip! on_red rindex squish to_c toutf32 white
blink chr each_byte gray is_utf8? magenta on_white rjust squish! to_csv toutf8 whiteish
block_scanf classify each_char grayish iseuc match on_yellow rpartition start_with? to_d tr yellow
blue clear each_codepoint green isjis mb_chars ord rstrip starts_with? to_date tr! yellowish
或者你想到的任何其他實體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/307609.html
標籤:
上一篇:我使用的是哪個Ruby版本?
