6
6

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.

= で終わるメソッドの返り値は (だいたい) 無視される

Posted at

= で終わるメソッドの返り値に関わらず、代入式の値は右辺の値になる。

Methods that end with an equals sign indicate an assignment method. For assignment methods the return value is ignored, the arguments are returned instead.
File: methods.rdoc [Ruby 2.2.0]

class Person
  def name=(v)
    @name = v
    "Name assigned" # 返り値
  end
end
person = Person.new
p(person.name = "labocho") #=> "labocho"
class Person
  attr_reader :id
  def id=(v)
    @id = v.to_i
  end
end
person = Person.new

# 代入式が連続する場合
# いっけん id == person.id に見えるが...
id = person.id = "123"
p person.id #=> 123
p id #=> "123"

ただし send を使った場合は通常のメソッドと同様、メソッドの最後の文の値になる。

class Person
  def name=(v)
    @name = v
    "Name assigned"
  end
end

person = Person.new
p(person.send(:name=, "labocho")) #=> "Name assigned"
6
6
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
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?