fugafuga.write

日々のログ

Ruby 2.x.x 入門 - オブジェクトや変数を扱う -

Rubyでのオブジェクト、変数などについて学習していきます。



オブジェクトについて

Rubyでは全てがオブジェクトで表現されます。
pryを使ってオブジェクトの中身を覗いてみます。

数値オブジェクト

数値の「5」オブジェクト内に移動する

[2] pry(main)> cd 5
[3] pry(5):1> ls
Comparable#methods: between?
Numeric#methods:
  +@      conj       imaginary     pretty_print_cycle  rectangular
  abs2    conjugate  nonzero?      quo                 remainder
  angle   eql?       phase         real                singleton_method_added
  arg     i          polar         real?               step
  coerce  imag       pretty_print  rect                to_c
Integer#methods:
  ceil         downto  gcdlcm    next       pred         times   to_r
  chr          floor   integer?  numerator  rationalize  to_i    truncate
  denominator  gcd     lcm       ord        round        to_int  upto
Fixnum#methods:
  %  **  -@  <<   ==   >=  ^        div     fdiv       modulo  succ  zero?
  &  +   /   <=   ===  >>  __pry__  divmod  inspect    odd?    to_f  |
  *  -   <   <=>  >    []  abs      even?   magnitude  size    to_s  ~
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_

floor など数値の処理に関係するメソッドを持っているのがわかります。


文字列オブジェクト

文字列の「文字列」オブジェクト内に移動する

[7] pry(5):1> cd "文字列"
[8] pry("文字列"):2> ls
Comparable#methods: <  <=  >  >=  between?
String#methods:
  %            chop!           getbyte    reverse      succ
  *            chr             gsub       reverse!     succ!
  +            clear           gsub!      rindex       sum
  <<           codepoints      hash       rjust        swapcase
  <=>          concat          hex        rpartition   swapcase!
  ==           count           include?   rstrip       to_c
  ===          crypt           index      rstrip!      to_f
  =~           delete          insert     scan         to_i
  []           delete!         inspect    setbyte      to_r
  []=          downcase        intern     shell_split  to_s
  ascii_only?  downcase!       length     shellescape  to_str
  b            dump            lines      shellsplit   to_sym
  bytes        each_byte       ljust      size         tr
  bytesize     each_char       lstrip     slice        tr!
  byteslice    each_codepoint  lstrip!    slice!       tr_s
  capitalize   each_line       match      split        tr_s!
  capitalize!  empty?          next       squeeze      unpack
  casecmp      encode          next!      squeeze!     upcase
  center       encode!         oct        start_with?  upcase!
  chars        encoding        ord        strip        upto
  chomp        end_with?       partition  strip!       valid_encoding?
  chomp!       eql?            prepend    sub
  chop         force_encoding  replace    sub!
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_

size など文字列の処理に関係するメソッドを持っているのがわかります。

配列、ハッシュオブジェクト

[1,2,3,4] の配列オブジェクト内に移動する

[6] pry(main)> cd [1,2,3,4]
[7] pry(#<Array>):1> ls
Enumerable#methods:
  all?            each_entry        find_all  max      minmax_by     sort_by
  any?            each_slice        flat_map  max_by   none?
  chunk           each_with_index   grep      member?  one?
  collect_concat  each_with_object  group_by  min      partition
  detect          entries           inject    min_by   reduce
  each_cons       find              lazy      minmax   slice_before
Array#methods:
  &            count       include?            reject                slice
  *            cycle       index               reject!               slice!
  +            delete      insert              repeated_combination  sort
  -            delete_at   inspect             repeated_permutation  sort!
  <<           delete_if   join                replace               sort_by!
  <=>          drop        keep_if             reverse               take
  ==           drop_while  last                reverse!              take_while
  []           each        length              reverse_each          to_a
  []=          each_index  map                 rindex                to_ary
  assoc        empty?      map!                rotate                to_s
  at           eql?        pack                rotate!               transpose
  bsearch      fetch       permutation         sample                uniq
  clear        fill        place               select                uniq!
  collect      find_index  pop                 select!               unshift
  collect!     first       pretty_print        shelljoin             values_at
  combination  flatten     pretty_print_cycle  shift                 zip
  compact      flatten!    product             shuffle               |
  compact!     frozen?     push                shuffle!
  concat       hash        rassoc              size
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_



{:one => 1, :two => 2} のハッシュオブジェクト内に移動する。

[3] pry(main)> cd {:one => 1, :two => 2}
[5] pry(#<Hash>):1> ls
Enumerable#methods:
  all?            drop_while        find_index  max_by     reverse_each
  any?            each_cons         first       min        slice_before
  chunk           each_entry        flat_map    min_by     sort
  collect         each_slice        grep        minmax     sort_by
  collect_concat  each_with_index   group_by    minmax_by  take
  count           each_with_object  inject      none?      take_while
  cycle           entries           lazy        one?       zip
  detect          find              map         partition
  drop            find_all          max         reduce
Hash#methods:
  ==                    delete_if   include?  pretty_print        to_a
  []                    each        index     pretty_print_cycle  to_h
  []=                   each_key    inspect   rassoc              to_hash
  assoc                 each_pair   invert    rehash              to_s
  clear                 each_value  keep_if   reject              update
  compare_by_identity   empty?      key       reject!             value?
  compare_by_identity?  eql?        key?      replace             values
  default               fetch       keys      select              values_at
  default=              flatten     length    select!
  default_proc          has_key?    member?   shift
  default_proc=         has_value?  merge     size
  delete                hash        merge!    store
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


:hoge は「シンボル」と呼ばれ、日本語が使えない文字列オブジェクトのようなイメージ。
ハッシュのキーとして使われることが多いとのこと。

正規表現オブジェクト

[10] pry(main)> cd Regexp.new("Ruby")
[11] pry(#<Regexp>):1> ls
Regexp#methods:
  ==   casefold?  fixed_encoding?  match           options  ~
  ===  encoding   hash             named_captures  source
  =~   eql?       inspect          names           to_s
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


時刻オブジェクト

[2] pry(main)> t = Time.now
=> 2014-09-03 23:15:42 +0900
[3] pry(main)> cd t
[4] pry(#<Time>):1> ls
Comparable#methods: <  <=  ==  >  >=  between?
Time#methods:
  +        friday?     hash       monday?    succ       tuesday?    wday
  -        getgm       hour       month      sunday?    tv_nsec     wednesday?
  <=>      getlocal    inspect    nsec       thursday?  tv_sec      yday
  asctime  getutc      isdst      round      to_a       tv_usec     year
  ctime    gmt?        localtime  saturday?  to_f       usec        zone
  day      gmt_offset  mday       sec        to_i       utc
  dst?     gmtime      min        strftime   to_r       utc?
  eql?     gmtoff      mon        subsec     to_s       utc_offset
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


シンボルオブジェクト

[1] pry(main)> cd :sym
[2] pry(:sym):1> ls
Comparable#methods: <  <=  >  >=  between?
Symbol#methods:
  <=>  []          downcase  inspect  next                succ      to_sym
  ==   __pry__     empty?    intern   pretty_print_cycle  swapcase  upcase
  ===  capitalize  encoding  length   size                to_proc
  =~   casecmp     id2name   match    slice               to_s
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


範囲オブジェクト

[1] pry(main)> cd 1..10
[2] pry(#<Range>):1> ls
Enumerable#methods:
  all?            drop_while        find_index  minmax        slice_before
  any?            each_cons         flat_map    minmax_by     sort
  chunk           each_entry        grep        none?         sort_by
  collect         each_slice        group_by    one?          take
  collect_concat  each_with_index   inject      partition     take_while
  count           each_with_object  lazy        reduce        to_a
  cycle           entries           map         reject        zip
  detect          find              max_by      reverse_each
  drop            find_all          min_by      select
Range#methods:
  ==     bsearch  end           first     inspect  member?       size
  ===    cover?   eql?          hash      last     min           step
  begin  each     exclude_end?  include?  max      pretty_print  to_s
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


Rubyでは、数値の範囲を「..」や「...」を使って表現することができます。

例外オブジェクト

[1] pry(main)> e = Exception.new
=> #<Exception: Exception>
[2] pry(main)> cd e
[3] pry(#<Exception>):1> ls
Exception#methods:
  ==  backtrace  exception  inspect  message  respond_to?  set_backtrace  to_s
self.methods: __pry__
locals: _  __  _dir_  _ex_  _file_  _in_  _out_  _pry_


例外処理を行う場合に、使用するオブジェクトです。

変数について

Ruby で使用される変数は以下の4種類です。

ローカル変数

変数名の先頭がアルファベットの小文字か_(アンダースコア)で始まる。

hoge = 1
_foo = "fuga"


グローバル変数

変数名の先頭が $ で始まる。

$g_hoge = false


インスタンス変数

変数名の先頭が @ で始まる。

@hoge = "member"


クラス変数

変数名の先頭が @@ で始まる。

@@hoge = "var"


代入することができないのですが、変数という名前がついている特殊なものがあります。

擬似変数

niltruefalseself