2016-03-08 68 views
0
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}?" 

使用內部評級法,這是我所得到的: 「!自旋Woosh」爲什麼Ruby在字符串之前打印object.method?

**spins! Woosh!                             
This bike is white and it has 11 gears. Oh, and it                    
has a compact design. Did I mention that my bike ?** 

爲什麼來之前的字符串,爲什麼不是IN的字符串?

回答

4

因爲您沒有從方法中返回字符串,所以您直接打印它。

要做你想做的事,只需從你的spin方法中刪除puts,你很好。

class Bike 
    attr_accessor :color, :gear_numbers, :style 

    def spin 
    "spins! Woosh!" 
    end 
end 
2

因爲插入字符串Ruby需要調用spin。然後Ruby將spin方法的返回值(即nil,因爲puts返回nil)包含到字符串中並打印生成的字符串。

1

這裏的問題是,字符串內插需要在字符串傳遞到主要的puts之前完全完成。作爲計算內部內容的一部分,它必須按照它們出現的順序執行每個引用的方法。

spin方法導致立即puts,它不返回任何東西,因爲這是如何puts作品。如果你想提供一個字符串去那裏,只是把它:

def spin 
    " spins! Woosh!" 
end 

覺得這個字符串插值:

"a #{b} C#{d} e" 

這大致相當於:

"a " + b.to_s + " c " + d.to_s + " e" 

在哪裏那些.to_s調用是強制它變成一個字符串。在返回整個字符串之前,您會期望執行bd

當預測將執行什麼代碼時,首先將執行追蹤到底部,然後再進行備份。簡單的程序以非常可預測的方式工作。

+1

「簡單的程序以非常可預測的方式工作。」 ...和副作用以複雜的方式工作,因此使用副作用的程序並不簡單。這個問題很好地證明了這一點,這再次說明爲什麼應該儘可能地避免副作用。 –

相關問題