2014-05-08 39 views
0

我不明白,为什么在这短短的Ruby脚本不利用“劳伦斯”:它为什么不把它大写?

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') 

,我得到这样的输出:

60 
Larry 
lawrence #why not Lawrence ? 

感谢

+0

'把player2.his_name#=> Lawrence' – xlembouras

回答

2

的结果表达式x = yy并且表达式o.x = y的结果是y-如果它是变量赋值或设置者,则无关紧要。 (通过上述形式调用setter的结果会被丢弃。)

比较:

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

你的方法作品和它大写的名字,林心如只是忽略你的方法的返回值。从documentation for methods

注意,对于分配方法的返回值将始终是 忽略。相反的说法将被退回:

def a=(value) 
    return 1 + value 
end 

p(a = 5) # prints 5 
+0

感谢。要证明这一点我输入: 'player2 = Player.new( '拉里',60) 提出player2.his_name 提出player2.his_name =( '劳伦斯') 放player2.his_name ' 并获得: “ Larry Lawrence Lawrence ' – luca

+0

对不起,格式不正确。 – luca

+0

@luca使用反引号格式化代码,请参阅[注释格式](http://stackoverflow.com/editing-help#comment-formatting) – Stefan

相关问题