Ruby on Rails

Ruby on Railsの面白いメソッド

更新日:

こんにちは、Shinyaです。福岡は曇天です

今回はゆるーくRuby on Railsの一風変わったメソッドを3つくらい見ていきましょう

methodsメソッド

使い方

オブジェクト.methods

できること

メソッドを使ったオブジェクトが使用可能なメソッドの一覧を返す

railsコンソールで試してみた↓

文字列の例

irb(main):001:0> string="string"
=> "string"
irb(main):002:0> string.methods
=> [:to_json, :squish!, :remove!, :truncate_words, :camelcase, :titlecase,
 :parameterize, :from, :mb_chars, :is_utf8?, :%, :*, :+, :html_safe,
 :strip_heredoc, :to_c, :exclude?, :indent!, :truncate, :remove,
 :shellsplit, :to, :shellescape, :+@, :-@, :<=>, :<<, :==, :===, :=~,
 :[], :[]=, :empty?, :eql?, :freeze, :inspect, :intern, :inquiry, :length,
 :size, :succ, :pathmap, :to_str, :to_sym, :to_s, :to_i, :to_r, :to_f,
 :pathmap_explode, :pathmap_partial, :indent, :pathmap_replace, :hash,
 :include?, :at, :last, :classify, :acts_like_string?, :ext, :to_blob,
 :as_json, :ends_with?, :count, :blank?, :partition, :in_time_zone,
 :first, :to_datetime, :sum, :next, :casecmp, :casecmp?, :insert,
 :bytesize, :match, :match?, :succ!, :next!, :upto, :index, :rindex,
 :replace, :clear, :chr, :getbyte, :setbyte, :byteslice, :scrub, :scrub!,
 :squish, :dump, :undump, :to_d, :upcase, :to_date, :downcase, :swapcase,
 :upcase!, :capitalize, :capitalize!, :encode, :downcase!, :oct,
 :swapcase!, :lines, :bytes, :split, :codepoints, :grapheme_clusters,
 :reverse, :reverse!, :hex, :underscore, :crypt, :ord, :prepend, :chars,
 :scan, :start_with?, :end_with?, :center, :sub, :gsub, :chop, :chomp,
 :strip, :concat, :lstrip, :delete_prefix, :delete_suffix, :rstrip,
 :gsub!, :chop!, :chomp!, :rjust, :strip!, :upcase_first, :rstrip!,
 :tableize, :ljust, :sub!, :to_time, :delete, :foreign_key,
 :delete_suffix!, :lstrip!, :tr_s, :delete_prefix!, :each_line,
 :safe_constantize, :tr_s!, :delete!, :squeeze!, :tr!, :tr, :slice,
 :slice!, :squeeze, :each_byte, :valid_encoding?, :each_codepoint,
 :each_grapheme_cluster, :ascii_only?, :b, :rpartition, :encoding,
 :unicode_normalized?, :unicode_normalize!, :camelize, :each_char,
 :force_encoding, :dasherize, :constantize, :humanize, :singularize,
 :deconstantize, :encode!, :pretty_print, :titleize, :pluralize,
 :unicode_normalize, :demodulize, :starts_with?, :unpack, :unpack1,
 :to_json_raw_object, :to_json_raw, :<=, :>=, :between?, :<, :>,
 :clamp, :`, :html_safe?, :with_options, :acts_like?, :present?, :in?,
 :to_param, :presence, :presence_in, :duplicable?, :to_query,
 :instance_values, :instance_variable_names, :deep_dup, :to_yaml,
 :pretty_print_cycle, :pretty_print_inspect,
 :pretty_print_instance_variables, :load_dependency, :require_or_load,
 :unloadable, :require_dependency, :try!, :try, :instance_variable_set,
 :instance_variable_defined?, :remove_instance_variable, :instance_of?,
 :kind_of?, :is_a?, :tap, :instance_variable_get, :singleton_method,
 :method, :public_method, :define_singleton_method, :public_send,
 :class_eval, :extend, :gem, :byebug, :remote_byebug, :debugger,
 :to_enum, :enum_for, :pretty_inspect, :!~, :respond_to?,
 :object_id, :send, :display, :nil?, :class, :singleton_class,
 :clone, :dup, :itself, :yield_self, :taint, :tainted?, :untaint,
 :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods,
 :protected_methods, :private_methods, :public_methods,
 :instance_variables, :!, :equal?, :instance_eval, :instance_exec,
 :!=, :__id__, :__send__]

整数の例

irb(main):001:0> integer=1
=> 1
irb(main):002:0> integer.methods
=> [:to_s, :to_json, :-@, :**, :<=>, :upto, :<<, :<=, :>=, :==, :chr, :===,
 :>>, :[], :to_d, :to_bn, :%, :&, :inspect, :+, :ord, :-, :numerator, :/,
 :*, :rationalize, :gcd, :lcm, :gcdlcm, :denominator, :size, :succ,
 :multiple_of?, :<, :>, :months, :years, :to_int, :coerce, :divmod,
 :to_i, :fdiv, :modulo, :remainder, :abs, :magnitude, :month, :integer?,
 :ordinalize, :year, :to_r, :floor, :ceil, :round, :truncate, :to_f, :^,
 :odd?, :even?, :allbits?, :anybits?, :nobits?, :downto, :times, :pred,
 :pow, :bit_length, :digits, :ordinal, :next, :div, :|, :~, :+@,
 :pretty_print, :minute, :weeks, :hours, :minutes, :eql?, :bytes,
 :kilobytes, :kilobyte, :megabyte, :gigabytes, :gigabyte, :terabytes,
 :singleton_method_added, :terabyte, :week, :fortnights, :fortnight,
 :arg, :in_milliseconds, :exabytes, :exabyte, :rectangular, :rect, :polar,
 :real, :imaginary, :imag, :abs2, :angle, :phase, :conjugate, :to_c,
 :second, :conj, :seconds, :pretty_print_cycle, :as_json, :i, :real?,
 :zero?, :nonzero?, :finite?, :infinite?, :step, :positive?, :negative?,
 :blank?, :hour, :day, :petabytes, :byte, :days, :html_safe?, :clone,
 :dup, :petabyte, :quo, :megabytes, :between?, :clamp, :`, :with_options,
 :acts_like?, :present?, :in?, :to_param, :presence, :presence_in,
 :duplicable?, :to_query, :instance_values, :instance_variable_names,
 :deep_dup, :to_yaml, :pretty_print_inspect,
 :pretty_print_instance_variables, :load_dependency, :require_or_load,
 :unloadable, :require_dependency, :try!, :try, :instance_variable_set,
 :instance_variable_defined?, :remove_instance_variable, :instance_of?,
 :kind_of?, :is_a?, :tap, :instance_variable_get, :singleton_method,
 :method, :public_method, :define_singleton_method, :public_send,
 :class_eval, :extend, :gem, :byebug, :remote_byebug, :debugger,
 :to_enum, :enum_for, :pretty_inspect, :=~, :!~, :respond_to?,
 :freeze, :object_id, :send, :display, :nil?, :hash, :class,
 :singleton_class, :itself, :yield_self, :taint, :tainted?, :untaint,
 :untrust, :untrusted?, :trust, :frozen?, :methods, :singleton_methods,
 :protected_methods, :private_methods, :public_methods,
 :instance_variables, :!, :equal?, :instance_eval, :instance_exec,
 :!=, :__id__, :__send__]

railsコンソールで使っているので、ここにはrubyでは使えないrails独自のメソッドも含まれています

methodsメソッドで一覧表示して、気になったのメソッドを調べるだけでも勉強になりますよ

pluralizeメソッド

使い方

railsコンソールで使ってみた

irb(main):014:0> "man".pluralize
=> "men"
irb(main):015:0> "man".pluralize(1)
=> "man"
irb(main):016:0> "man".pluralize(2)
=> "men"
irb(main):017:0> helper.pluralize(0,"man")
=> "0 men"
irb(main):018:0> helper.pluralize(1,"man")
=> "1 man"

できること

英単語を単数形から複数形にする
個数を表す引数を与えると単複を判断して値を返す

注:railsのデフォルト言語設定が英語でないと機能しない。日本語化してるときはロケールを指定して使う↓

irb(main):019:0> helper.pluralize(3,"woman",locale: :en)
=> "3 women"

大半の英単語には対応している模様

これ使ったら英語のテスト楽じゃね?っていう何気に凄いメソッド

shuffleメソッド

使い方

irb(main):020:0> [1,2,3,4,5].shuffle
=> [3, 4, 2, 5, 1]
irb(main):021:0> ["a","b","c"].shuffle
=> ["c", "b", "a"]

できること

その名の通り配列の順序をシャッフルする

何に使うのか想像を掻き立てられるメソッドです

ランダム性が必要な処理に使えそうですね

最後に

以上がRuby on Railsの面白いメソッド3つでした!

他にもメソッドは沢山あるので、たまには息抜きで面白いメソッドを探して遊んでみてもいいかもしれませんね

案外そういう遊びみたいな勉強は身につくものですから

それでは、また

-Ruby on Rails
-

Copyright© 初心者のためのプログラミング独学ブログ , 2023 All Rights Reserved Powered by STINGER.