【问题标题】:Ruby RPN Calculator: array of arrays, shift & to_i problemsRuby RPN 计算器:数组数组、移位和 to_i 问题
【发布时间】: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

【问题讨论】:

标签: ruby arrays class


【解决方案1】:

问题 #1 > [] &lt;&lt; ["1", "3", "+"] #=&gt; [["1", "3", "+"]]

#<< 插入为什么不使用这些元素初始化数组? arrray = ["1", "3", "+"]

问题 #1.5 > [["1", "3", "+"]].size #=&gt; 1

问题 #2 > i = [["1", "3", "+"]].first #=&gt; ["1", "3", "+"] 所以是的,这是因为问题 1 问题 #2... > i.shift #=&gt; ["1"]

ISSUE #3 #to_i 或 #each 不会永久修改您需要的变量queue.map! http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-map-21

【讨论】:

  • 为什么是array = [],然后是array += some_stuff 而不仅仅是array = some_stuff
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-18
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
相关资源
最近更新 更多