【发布时间】:2014-10-10 16:08:43
【问题描述】:
我正在制作一个 Ruby 逆波兰表示法计算器,但在档案中找不到我的问题的答案。我写了一个游戏计划并正在填写代码。我目前的 3 个问题是:
- 我的数组是一个数组的数组,我不知道为什么。当我在课堂外尝试这个时,它可以正常工作。也许这与课程的运作方式有关?我看过一些视频,花了几个小时试图了解类的特征。
- 当我尝试将项目移动到新数组时,只有一个成功。也许这与第一个问题有关。
- 使用 to_i 将我的数组元素转换为整数在这种情况下不起作用。我可以让它解决其他问题。我刚刚开始上课,因此我遇到了很多问题。我也在尝试学习正则表达式,因为那里的许多其他 RPN 计算器在他们的解决方案中使用它 - 但我还没有理解。
代码:
class RPNCalculator
def initialize(problem)
@problem = problem
end
def resolve
array = []
array << @problem.split(" ")
operations = ["+", "-", "*"]
queue = []
@array = array
@operations = operations
@queue = queue
p array # => [["1", "3", "+"]] ISSUE #1: my test print shows array of an array.
# iterate through the array
array.each do |i|
# if array elements don't match a operations element, push them into the queue.
if operations.include? i
# once you have a match on the function, launch a method
# make 3 new RPN methods, one each for + - *
# method launched should affect last 2 items in the queue.
# result of that method gets pushed to the end of the queue.
else queue.push(i.shift)
end
queue.each { |x| x.to_i }
p queue # => ["1"] ISSUE #2: only 1 was pushed in. Perhaps because issue #1?
# ISSUE #3: my strings did not convert to integers.
end
# return the remaining value in the queue as the answer
end
# placeholder for method +
# placeholder for method -
# placeholder for method *
end
test = "1 3 +"
mytest = RPNCalculator.new(test)
mytest.resolve
【问题讨论】:
-
您可能想查看我对this RPN question 的回答以获取想法。
-
请正确格式化您的代码,这很难读。如果您不确定,请参阅github.com/bbatsov/ruby-style-guide。