如果你真的想用__method__
,你的方法是正確的,合理的可讀性。要符合常規的Ruby指南,你可以只取出return
S和使用2個空格作爲縮進(如@ sagarpandya82在評論中提到):
def recurse(value)
if value < 5
self.send(__method__, value + 1)
else
value
end
end
我看不出有任何理由要在這裏使用self.send(__method__)
,所以你可以寫:
def recurse(value)
if value < 5
recurse(value + 1)
else
value
end
end
其實,我會說你根本不需要遞歸。你所有的方法,它只是不斷增加1的值,直到達到5.如果該值大於5,則返回值:
對於整數:
def no_recurse(value)
[value, 5].max
end
no_recurse(4)
# 5
no_recurse(-3)
# 5
no_recurse(7)
# 7
no_recurse(-2**1000)
# 5
no_recurse(4.5)
# 5 # <- That's wrong
對於花車,你會只需要將小數部分加到5
即可。
def no_recurse(value)
[value, 5 + value % 1].max
end
no_recurse(4.5)
# 5.5
no_recurse(5.5)
# 5.5
no_recurse(6)
# 6
no_recurse(-7)
# 5
的[獲取當前執行方法的名稱]可能的複製(http://stackoverflow.com/questions/199527/get-the-name-of-the-currently:這將任意數量的工作-executing-method) –
我認爲你的解決方案讀得很好。作爲一個附註,你可以省略'return's,並且你應該使用2個空格來縮進。 –
很多時候遞歸方法並不像迭代那樣簡潔或有效。 Ruby的Enumerable庫提供了比大多數更多的功能,並且可以在列表上創建奇蹟。在許多情況下,遞歸事物可以表示爲一系列列表轉換。 – tadman