.methods メソッド
オブジェクトに対して使えるメソッドを一覧表示してくれる
「methods」メソッド
例えば、配列 (array) を作ってみる!
puts "数字を入力してください" input = gets.to_i array = -5..input
配列の範囲指定に使える「..」の書き方か思い出しつつ
これを、
p array.methods.sort
順番を昇順にする「sort」メソッドとかも思い出しつつ、
(「methods」メソッドでもちろん出る)
pで出力すると、
MacBook-Pro:desktop me$ ruby t.rb 数字を入力してください 5 ------------------出力結果---------------------------- [:!, :!=, :!~, :<=>, :==, :===, :=~, :__id__, :__send__, :all?, :any?, :begin, :bsearch, :chunk, :chunk_while, :class, :clone, :collect, :collect_concat, :count, :cover?, :cycle, :define_singleton_method, :detect, :display, :drop, :drop_while, :dup, :each, :each_cons, :each_entry, :each_slice, :each_with_index, :each_with_object, :end, :entries, :enum_for, :eql?, :equal?, :exclude_end?, :extend, :find, :find_all, :find_index, :first, :flat_map, :freeze, :frozen?, :grep, :grep_v, :group_by, :hash, :include?, :inject, :inspect, :instance_eval, :instance_exec, :instance_of?, :instance_variable_defined?, :instance_variable_get, :instance_variable_set, :instance_variables, :is_a?, :itself, :kind_of?, :last, :lazy, :map, :max, :max_by, :member?, :method, :methods, :min, :min_by, :minmax, :minmax_by, :nil?, :none?, :object_id, :one?, :partition, :private_methods, :protected_methods, :public_method, :public_methods, :public_send, :reduce, :reject, :remove_instance_variable, :respond_to?, :reverse_each, :select, :send, :singleton_class, :singleton_method, :singleton_methods, :size, :slice_after, :slice_before, :slice_when, :sort, :sort_by, :step, :taint, :tainted?, :take, :take_while, :tap, :to_a, :to_enum, :to_h, :to_s, :trust, :untaint, :untrust, :untrusted?, :zip]
p出力でなくて
puts array.methods.sort.reverse
↑のようにputs出力であれば、
MacBook-Pro:desktop me$ ruby t.rb 数字を入力してください 3 -----------------出力結果---------------------- zip untrusted? untrust untaint trust to_s to_h 〜(中略)〜 bsearch begin any? all? __send__ __id__ =~ === == <=> !~ != !
「reverse」メソッドで降順にしつつ、
このように出力される!
これからわかることは、
putsは、
引数のオブジェクトを改行を加えて出力。
返り値は「nil」
pは、
引数のオブジェクトをわかりやすく標準出力。
メソッドが配列に入ってるとこれで知れたり。デバッグ用とか。
返り値も返す。
とにかくまずは「methods」メソッドをぶつけて、
使えそうなやつを見つける。
すぐそのメソッドをそのまま検索にかけ
リファレンスなどで正しい使い方を確認。
実際に使って出力を見てみる。
どんなメソッドが使えそうかな?という感覚と
すぐリファレンスで使い方を探すスピード。
「methods」メソッド早く知っときたかった。