LoginSignup
3
3

More than 5 years have passed since last update.

Railsで2つのカラムの入れ替え

Posted at

Railsでカラムをbefore_createで入れ替えるという処理をしたくて、

date2, date1 = date1, date2

と書いたはいいが値の入れ替えは行われなかった。それどころかnilになってしまった。

self.date2, self.date1 = self.date1, self.date2

と、selfを付けると入れ替えができた。以下のプログラムでも同様の現象が起きた。

class Hoge
  attr_accessor :a, :b

  def func
    a, b = b, a
    p a, b #=> nil nil
    p self.a, self.b #=> 1 2
  end
end

h = Hoge.new
h.a, h.b = 1, 2
puts "#{h.a}, #{h.b}" #=> 1, 2
h.func
puts "#{h.a}, #{h.b}" #=> 1, 2

a, b = b, aの左辺値がローカル変数になってるからだと思うのだけれども、その直後のa, bがnilだった。バグ?

3
3
3

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