为什么Ruby打印object.method在字符串之前?
使用IRB,我得到的是:为什么Ruby打印object.method在字符串之前?,ruby,methods,Ruby,Methods,使用IRB,我得到的是: class Bike attr_accessor :color, :gear_numbers, :style def spin puts " spins! Woosh!" end end gw = Bike.new gw.color = "white" gw.gear_numbers = 11 gw.style = "compact" puts "This bike is #{gw.color} and it has #{gw.gear_num
class Bike
attr_accessor :color, :gear_numbers, :style
def spin
puts " spins! Woosh!"
end
end
gw = Bike.new
gw.color = "white"
gw.gear_numbers = 11
gw.style = "compact"
puts "This bike is #{gw.color} and it has #{gw.gear_numbers} gears. Oh, and it has a #{gw.style} design. Did I mention that my bike #{gw.spin}?"
为什么“spins!Woosh!”出现在字符串前面,为什么它不在字符串中?因为您不是从方法返回字符串,而是直接打印它 要做您想做的事情,只需从
spin
方法中删除put
,就可以开始了
**spins! Woosh!
This bike is white and it has 11 gears. Oh, and it
has a compact design. Did I mention that my bike ?**
因为要插入字符串,Ruby需要调用
spin
。然后Ruby包含spin
方法的返回值(即nil
,因为put
返回nil
)插入字符串并打印生成的字符串。这里的问题是,在字符串传递到主put
之前,需要完全完成字符串插值。作为弄清楚其中包含什么的一部分,它必须按照它们出现的顺序执行引用的每个方法
您的spin
方法会导致立即put
并且不会返回任何内容,因为put
就是这样工作的。如果您想提供一个字符串进入其中,只需将其保留:
class Bike
attr_accessor :color, :gear_numbers, :style
def spin
"spins! Woosh!"
end
end
想想这个字符串插值:
def spin
" spins! Woosh!"
end
这大致相当于:
"a #{b} c #{d} e"
其中,那些.to_s
调用将强制将其转换为字符串。您希望在返回整个字符串之前执行b
和d
当预测代码将要做什么时,首先跟踪执行到底部,然后进行备份。简单的程序以非常可预测的方式工作。“简单的程序以非常可预测的方式工作。”…而副作用以复杂的方式工作,因此使用副作用的程序并不简单。这个问题很好地证明了这一点,它再次说明了为什么应该尽可能避免副作用。
"a " + b.to_s + " c " + d.to_s + " e"