3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

プログラミングRuby 1.9 言語編 メモ

Last updated at Posted at 2012-03-24

initializeメソッドについて

p28より。

initialize は特殊なメソッドです。BookInStock.new を呼び出して新しいオブジェクトを生成す
ると、Ruby はいくらかメモリを割り当て、そこに初期化されていないオブジェクトを保持します。そし
て、そのオブジェクトの initialize メソッドを呼び出します。その際、newに渡された引数をすべて
initialize に渡します。

class BookInStock
    def initialize(isbn, price)
        @isbn = isbn
        @price = Float(price)
    end
end

book = BookInStock.new("12345", 500)
p book
#<BookInStock:0x000000021e8b40 @isbn="12345", @price=500> 

属性の読み書き

p32より。


#読み取り専用
attr_reader :isbn
#読み書き可
attr_accessor :price

仮想属性 

p32より。

class BookInStock
   attr_accessor :price
   def initialize(price)
     @price = price
   end
   def price_in_cents=(cents)
     @price = cents / 100.0
   end
 end

book = BookInStock.new(20)  

p book.price
#20

book.price_in_cents = 2000 
p book.price
#20

変数名とクラス、定数名

p17より。
変数名の先頭の文字でスコープが異なる。
また、クラス、定数名は大文字始まりで大文字区切り。

#ローカル
hoge

#グローバル
$hoge

#インスタンス
@hoge

#クラス
@@hoge

#クラス、定数名
HogeHoge

シンボル

p19より。

シンボルとは、事前に宣言する必要がなく、なおかつ一意であることが保証される定数名のことです。
:hoge

privateメソッドについて

p37より。

明示的なレシーバを指定して呼び出すことはできません。レシーバは常に自分自身(self)です。

アクセス制御の記法

p37〜38より。

class Hoge
  # 何も指定しない場合はpublic
  def hoge1
  end

  protected
  def hoge2
  end

  private
  def hoge3
  end

  public
  def hoge4
  end
end

class Hoge
  def hoge1
  end

  def hoge2
  end

  def hoge3
  end

  def hoge4
  end

  # まとめて指定することも可能
  public :hoge1
  protected :hoge2
  private :hoge3 :hoge4
end

変数について

p39〜41より。

変数はオブジェクトでしょうか。
Ruby では、答えは「ノー」です。変数は単にオブジェクトへの リファレンスにすぎません。
オブジェクトは大きなプール(多くの場合ヒープ)の中に浮かんでおり、変数によって参照されます。
hoge1 = "hogehoge"
hoge2 = hoge1

p hoge1
#hogehoge

p hoge2
#hogehoge

hoge1[0] = "f"

p hoge1
#fogehoge

p hoge2
#fogehoge

# freezeメソッド他から変更できないようにできる
hoge1.freeze

配列の添字

p43〜44より。

配列にはマイナスの添字もある。

arr = [1, 2, 3]

for hoge in 0..(arr.count - 1) do
  p arr[hoge]
end

#1
#2
#3

#負数の添字
for hoge in (arr.count * -1)..-1 do
  p arr[hoge]
end

#1
#2
#3

範囲を指定することも可能。

arr = [1, 2, 3]
p arr[1..2]

# [2, 3]

開始位置と個数を指定することも可能。

arr = [1, 2, 3]
p arr[1, 2]

# [2, 3]
3
3
11

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?