LoginSignup
0
0

More than 1 year has passed since last update.

Ruby:「Procオブジェクト」「シンボル」について

Last updated at Posted at 2023-04-24

Procオブジェクト

Procオブジェクトは、Rubyのオブジェクトの一種で、ブロックをオブジェクト化したものです。ブロックは、一連のコードを囲んで、それをメソッドに渡すために使用されます。しかし、ブロックは通常のオブジェクトではありません。Procオブジェクトを使うことで、ブロックを通常のオブジェクトとして扱い、変数に代入したり、メソッドの引数として渡すことができます。

square = Proc.new { |x| x * x }
puts square.call(5) # => 25

シンボル

シンボルは、Rubyのオブジェクトの一種で、イミュータブル(変更不可)な文字列のようなものです。シンボルは、先頭にコロン : を付けることで表現されます。シンボルは、メモリ効率が良く、同じ名前のシンボルは同じオブジェクトとして扱われるため、比較やハッシュのキーとして使う際に高速です。

person = {
  :name => "Alice",
  :age => 30,
  :city => "New York"
}

puts person[:name] # => "Alice"
puts person[:age]  # => 30

シンボルと文字列の違い

string1string2 は同じ内容の文字列ですが、異なるオブジェクトです。一方、symbol1symbol2 は同じ名前のシンボルで、同じオブジェクトです。これにより、シンボルはメモリ効率が良く、比較が高速になります。

string1 = "apple"
string2 = "apple"

puts string1 == string2 # => true
puts string1.object_id == string2.object_id # => false

symbol1 = :apple
symbol2 = :apple

puts symbol1 == symbol2 # => true
puts symbol1.object_id == symbol2.object_id # => true
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0