luc4leone
luc4leone

Reputation: 11

why it doesn't capitalize it?

I don't understand why in this short Ruby script it doesn't capitalize "lawrence":

class Player

  def his_name #the same as attr_reader :name ?
    @name
  end

  def his_name=(new_name) #the same as attr_writer :name ?
    @name = new_name.capitalize
  end

  def initialize(name, health=100)
    @name = name.capitalize
    @health = health
  end

player2 = Player.new('larry', 60)
puts player2.his_name 
puts player2.his_name=('lawrence')

and I get this output:

60
Larry
lawrence #why not Lawrence ?

Thanks

Upvotes: 0

Views: 49

Answers (2)

Stefan
Stefan

Reputation: 114178

Your method works and it does capitalize the name, Ruby just ignores your method's return value. From the documentation for methods:

Note that for assignment methods the return value will always be ignored. Instead the argument will be returned:

def a=(value)
  return 1 + value
end

p(a = 5) # prints 5

Upvotes: 3

user2864740
user2864740

Reputation: 61875

The result of the expression x = y is y and the result of the expression o.x = y is y - it doesn't matter if it is a variable assignment or a setter. (The result of a setter invoked via the above form is discarded.)

Compare with:

puts player2.his_name = 'lawrence' # -> lawrence
puts player2.his_name              # -> Lawrence

Upvotes: 2

Related Questions