ph3*_*3nx 3 ruby variables methods dry simplify
当我在Ruby中编写方法时,我常常想"我敢打赌这可以做得更简单".这是一个示例方法.它会添加从1开始的所有数字,直到数字为止n.有没有办法放弃变量solution?
def sum n
solution = 0
for i in 1..n do
solution += i
end
solution
end
Run Code Online (Sandbox Code Playgroud)
fal*_*tru 11
使用Enumerable#inject(或Enumerable#reduce):
(1..10).inject :+
# => 55
Run Code Online (Sandbox Code Playgroud)