【问题标题】:unexpected syntax error (意外的语法错误(
【发布时间】:2017-08-11 00:26:52
【问题描述】:

我在文件1_arithmetic.rb中写了以下代码:

def arithmetic1(n)
  (n * 5) - 20
end

使用 gem 工具 rake,我在控制台中输入了这个:

rake 1_arithmetic.rb:arithmetic1(5) 

然后,我收到一条错误消息:

syntax error near unexpected token `('

有人知道我哪里做错了吗?还是我使用rake的方式有问题?

【问题讨论】:

  • 你为什么要为此使用 rake?您在这里没有 rake 任务 (AFAICT)。使用irb,正确暴露方法,然后从那里获取。
  • 干杯,我读错了我的教程,它已经用我可以调用的 rake 任务进行了编程

标签: ruby rake


【解决方案1】:

我相信 rake 只能用于 rake 任务。您可以创建一个 rake 任务,然后调用您的方法。

require './1_arithmetic.rb'
task :arithmetic, [:n] => [:environment] do |t, args|
  arithmetic1(args[:n])
end

然后您将使用

调用任务
rake arithmetic[5]

参考:How can I run a ruby class from rake file?

参考:How to pass command line arguments to a rake task

【讨论】:

  • 如何在 Ruby 中解析? require 不需要end[n] 似乎引用了未知变量n[ 也是一个可能被解释的 shell 字符,所以如果在传入参数的目录中有一个名为 arithmetic5 的文件。
  • @engineersmnky 这就是我的想法。为何接受这是一个谜。
【解决方案2】:

如果您只想运行该方法,则不需要rake 来执行此操作,只需使用ruby 命令即可:

ruby -r./1_arithmetic.rb -e "puts arithmetic1(10)"

-r 选项告诉ruby 命令到require 文件,-e 选项告诉ruby 运行作为字符串传入的代码。

注意:发布的命令假设文件 1_arithmetic.rb 位于您运行命令的目录中,如果该文件路径 (./1_arithmetic.rb) 在其他位置,则需要弄乱该文件路径。

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 2011-10-16
    • 2013-10-12
    • 2011-07-21
    相关资源
    最近更新 更多