ruby基礎のメモ(3)
hash
pythonでいうならdictionary。
h={'one'=>1,'two'=>2,'three'=>3} puts h puts h['three']
出力は以下。
{"one"=>1, "two"=>2, "three"=>3}
3
num={a:1,b:2,c:3,d:4,e:5} num.each { | k, v | puts "key is #{k} ,and value is #{v}"}
出力は以下。
key is a ,and value is 1
key is b ,and value is 2
key is c ,and value is 3
key is d ,and value is 4
key is e ,and value is 5
num={a:1,b:2,c:3,d:4,e:5} num.each { | k, v | num.delete(k) if v>=3} puts num
出力は以下。
{:a=>1, :b=>2}
num={a:1,b:2,c:3,d:4,e:5} num2=num.select{ |k, v | v.odd?} puts num2
出力は以下。
{:a=>1, :c=>3, :e=>5}
class
class User def initialize(name) @name = name end def get_name @name end end user = User.new("jose") puts user.get_name
joseが返ってくる。
クラスのインスタンスをを生成するには.new()メソッドを使う。
initialize メソッドがある場合は、new メソッドを使うと必ず呼ばれる。
クラスのイニシャルは大文字。
class Book attr_accessor :title, :price def initialize(title, price) @title = title; @price = price end end book = Book.new("Programming Ruby", 1980) puts book.title puts book.price
Programming Ruby
1980
と出力される。
attr_accessorメソッドは、クラスやモジュールにインスタンス変数を読み書きするためのアクセサメソッドを定義する。
class Book attr_accessor :title, :price def initialize(title, price) @title = title; @price = price end end book = Book.new("Programming Ruby", 1980) book.price = 2000 puts book.price
2000
と出力される(1980から2000にアップデートされている)。