【问题标题】:No puts or gets inside instance method - Ruby实例方法中没有放置或获取 - Ruby
【发布时间】:2015-02-24 14:28:24
【问题描述】:

这真是把我逼疯了。

我有一个正在尝试调试的实例方法,但我遇到了一个问题,即我的 put 和 get 没有显示在实例方法中。

代码:

#! /usr/bin/env ruby

class Calculator
  def evaluate(string)
    ops = string.split(' ')
    ops.map! do |item|
      if item.is_a? Numeric
        return item.to_i
      else
        return item.to_sym
      end
    end

    puts "Got #{string}"         #Doesn't output
    puts "Converted to #{ops}"   #This too

    opscopy = ops.clone

    ops.each.with_index do |item, index|
      if item == :* || item == :/
        opscopy[index] = ops[index-1].send(item, ops[index+1])
        opscopy[index-1] = opscopy[index+1] = nil
      end
    end

    ops = opscopy.compact

    puts "After multi/div #{ops}"

    ops.each.with_index do |item, index|
      if item == :+ || item == :-
        opscopy[index] = ops[index-1].send(item, ops[index+1])
        opscopy[index-1] = opscopy[index+1] = nil
      end
    end

    puts "After +/- #{opscopy.compact}"

    opscopy.compact.first
  end
end

item = Calculator.new.evaluate "4 * 2"
puts "#{item} == 8"  #Prints :(

输出:

action@X:~/workspace/ruby$ ./calculator.rb                                                                                                                                                 
4 == 8    

【问题讨论】:

    标签: ruby


    【解决方案1】:

    map! 块中的 return 是问题所在。

    ops.map! do |item|
      if item.is_a? Numeric
        return item.to_i # returns from method
      else
        return item.to_sym # returns from method
      end
    end
    

    在调用 puts 之前,您正在返回 map! 块中的方法。

    map! 块更改为:

    ops.map! do |item|
      item.send(item.is_a?(Numeric) ? :to_i : :to_sym)
    end
    

    【讨论】:

    • 我是个呆子,谢谢。我以为你可以这样做,但我猜返回内部代码块会返回到方法闭包。
    • Blocks 和 Procs 从封闭的方法返回,Methods 和 lambdas 从自身返回。此外,块和 Procs 具有松散的参数检查,方法和 lambda 具有严格的参数检查。 (有用的助记符:Block 和 Procs 的行为相同,因为它们押韵,Lambda 和 Method 的行为相同,因为它们都是希腊语。)
    • @JörgWMittag 你所说的松散参数检查是什么意思?感谢助记符!我
    猜你喜欢
    • 2020-02-10
    • 2012-12-25
    • 2011-01-06
    • 2011-11-15
    • 2010-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    相关资源
    最近更新 更多