Ruby勉強日記

method/attributeがObjectに存在するかどうか確認するには

Object#respond_to?メソッドを使う class Hoge @foo attr_accessor :foo end a = Hoge.new a.respond_to?("foo") #=> true a.respond_to?("bar") #=> false

オブジェクトのコピー

cloneやdupだとshallow copyなので,deep copyするには a = "a" b = Marshal.load(Marshal.dump(a)) としなくてはいかん.つまり, shadow copy 参照.ポインタのような感じ? deep copy 複製.メモリ内のデータを異なる番地へコピーして,その番地の参照を…

JSONデータをparseするには

gem で json を install して # gem install json > 2 r = JSON.parse(json) pp ["name"] #=> "conceal-rs" などとなる.結果が Hash になるのに注意しないといかんな.

Objectのattributesの中身を変更する別の方法

配列で一気に attributes を変更したい場合などに book = Book.new book_atts = book.instance_variable_get(:@attributes) book_atts.each do |ba| book_atts[ba[0]] = array[ba[0]] end book.instance_variable_set(:@attributes, book_atts)

Ruby は property ではなく attribute

アクセサメソッドを簡単定義するには,attr_accessor メソッドを使う. class foo @bar = 0 attr_accessor :bar def f = foo.new f.bar = 10 p f.bar #=> 10