有ruby语法的问题

时间:2014-04-15 21:11:19

标签: ruby syntax

我是ruby的新手,不知道为什么我的代码在命令提示符下执行时无法正常工作。我得到的东西似乎说语法错误,意外的keyword_end,期待输入结束,我不知道如何正确修复它。任何帮助将不胜感激!

def temperature_conversion_functions
    def ftoc(x)
        "Converts freezing temperature"
        ftoc(32) == 0
        end

        "Converts boiling temperature"
        ftoc(212) == 100
        end

        "Converts body temperature"
        ftoc(98.6) == 37
        end

        "converts arbitrary temperature"
        ftoc(68) == 20
        end
    end

    def ctof(x)

        "converts freezing temperature"
        ctof(0) == 32
        end

        "converts boiling temperature"
        ctof(100) == 212
        end

        "converts arbitrary temperature"
        ctof(20) == 68
        end

        "converts body temperature"
        ctof(37) == 98.6
        end
    end

end

2 个答案:

答案 0 :(得分:2)

您有许多end个关键字,而这些关键字并非必要。代码可以包含在块中,如下所示:

x = 5
if x > 3
  puts "x is greater than 3!"
end

ifend附件类似,还有其他关键字,例如dodefclasswhile等,都有不同的用法。

其他东西:

  1. 您似乎正在使用字符串对代码进行评论,例如"Converts freezing temperature"。碰巧ruby会评估字符串,然后对它做任何事情。但是,编写注释的正确方法是使用#符号:

    # This is a comment. The line below is executed code
    puts "Printing out this string"
    
  2. 您正在递归ftocctof。小心造成无限循环!以下是递归的示例扩展:

    def ftoc(x)     # define the `ftoc(x)` method
      ftoc(32) == 9 # let's expand this line
    end
    

    ftoc(32)“展开”至ftoc(32) == 9,因为ftoc(x)的定义方式如下:

    def ftoc(x)
      ( ftoc(32) == 9 ) == 9 # "expanded" once
    end
    

    再次:

    def ftoc(x)
      ( ( ftoc(32) == 9 ) == 9 ) == 9 # "expanded" twice
    end
    

    并将永远地,无休止地继续

  3. 无需在ftoc方法中定义两个ctoftemperature_conversion_functions方法。如果您想组织几个相关的方法,我建议您使用module

    module TemperatureConversion
      def TemperatureConversion.ftoc(f) # This is an example. More idiomatic way is shown below
        return (f - 32) * 5.0/9
      end
    
      def self.ctof(c) # the 'self' in this line means/is-the-same-as 'TemperatureConversion'
        return c * 9.0/5 + 32
      end
    end
    
    # now you can use the module and its methods
    # convert freezing
    puts TemperatureConversion.ftoc(32) # will output 0.0
    

答案 1 :(得分:1)

正确对齐end个关键字 - 在相应的defclassif等关键字下 - 问题将会很明确。 (实际上有几个问题通过正确的缩进而非常明显。)

def ftoc(x)
    "Converts freezing temperature"
    # What this is "recusion and check" supposed to be anyway?
    # It's recursive because it's inside the same (ftoc) method.
    ftoc(32) == 0
end

    "Converts boiling temperature"
    ftoc(212) == 100
    # Uhh, where does this `end` go? It's "unexpected".
    end

无论如何,请考虑转换函数应仅为a simple equation

def ftoc(f)
    return (f - 32) * 5.0/9
end

然后可以这样使用

puts "42f is #{ftoc(42)}c"