简体   繁体   English

在ruby方法中传递参数

[英]Pass arguments in ruby method

I want to send 2 params from CLI when I start rake task. 启动rake任务时,我想从CLI发送2个参数。 I tried this code: 我尝试了这段代码:

namespace :tnx do

  require_relative "transactions.rb"
  include Cnp_transactions_modes

  task :generate, [:clean_all] => [:environment]  do |t, args|

    if args[: clean_all] == 'true'
      // something
    end

    if args[:times].empty?
      Cnp_transactions_modes.create_transactions(args[:times])
    end    
  end
end

But I get error: 但是我得到了错误:

rake aborted!
NoMethodError: undefined method `empty?' for nil:NilClass

How I can solve this Issue? 我该如何解决这个问题?

The error comes from the fact that if args[:times] is nil , empty? 该错误来自以下事实:如果args[:times]nil ,则为empty? cannot be called on args[:times] because empty? 不能在args[:times]上调用,因为为empty? isn't defined for nil object. 没有为nil对象定义。 In Rails, you could use blank? 在Rails中,您可以使用blank? to check if it's nil or empty . 检查它是否为nil或为empty

This should be enough : 这应该足够了:

if args[:times]

You don't need to check if args[:times] is empty, you need to check it's defined. 您无需检查args[:times]是否为空,只需检查其是否已定义。

Note that it's the opposite of your condition, but it's probably more logical that way. 请注意,这与您的情况相反,但是这样做可能更合乎逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM