我有几个step_1
-基于x
和y
变量的方法。
step_2
基于 step_1
方法创建新方法,但不需要变量(只是通过)!
同样适用于step_3
(基于step_2
-methods)。
我的问题是我有大约 20 个 step_2
方法,其中包含数十个 step_1
方法(5 种不同类型)。对于每一个,我都必须传递相同的两个变量。
我需要这种结构来进行迭代。
现在,有没有办法不使用全局变量,直接将step_3(x, y)
中的变量交给step_1(x, y)
?
# example
def step_1 (x, y)
return x + y
end
def step_2 (*foo)
return step_1(*foo)
end
def step_3 (*foo)
return step_2(*foo)
end
x, y = 2, 2 # example
puts step_3(x, y) # ==> 4
谢谢你的建议
最佳答案
当我读到“我必须传递相同的两个变量”时,这自然会让人想到创建一个可以传递的简单容器的想法:
class NumberTuple
attr_accessor :x
attr_accessor :y
def initialize(x, y)
@x = x
@y = y
end
end
tuple = NumberTuple.new(2,2)
step_3(tuple)
这通常会得出这样的结论:创建一个简单的计算类,可以将所有这些状态内化。这就是类实例擅长的地方:
class NumberCalculator
def initialize(x, y)
@x = x
@y = y
end
def step_3
step_2
end
def step_2
step_1
end
def step_1
@x + @y
end
end
calculator = NumberCalculator.new(2,2)
calculator.step_3
关于ruby - 在嵌套函数中移交变量的适当解决方案(在 ruby 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16240381/