Ruby中的语法错误。意外的keyword_end,期待输入结束

时间:2015-12-29 19:47:36

标签: ruby

我正在学习Ruby中的模块。

模块代码很好,但是当我拆分并制作文件时 它返回了语法错误:

C:/Desktop/Ruby/Function/5.rb:1:in `require_relative': C:/Desktop/Ruby/Function/Auth.rb:13: syntax error, unexpected keyword_end, expecting end-of-input (SyntaxError)
    from C:/Desktop/Ruby/Function/5.rb:1:in `<main>'

这是Auth.rb:

module Auth
  module_function()

  def login(id)
    members = ['abc', 'def', 'ghi']

    for member in members do
      if (id == member)
        return true
      end
    end
    return false
  end
end

这是5.rb:

require_relative 'Auth'

puts "Input your ID"

input_id = gets.chomp()

if Auth.login(input_id)
  puts "Hello, " + input_id
else
  puts "Who are you?"
end

1 个答案:

答案 0 :(得分:0)

您无法使用module Auth()定义模块:

irb(main):001:0> module Auth()
irb(main):002:1> end
SyntaxError: (irb):1: syntax error, unexpected '\n', expecting :: or '[' or '.'

irb(main):001:0> module Auth()
irb(main):002:1>   def login(id)
irb(main):003:2>   end
irb(main):004:1> end
SyntaxError: (irb):1: syntax error, unexpected '\n', expecting :: or '[' or '.'
(irb):4: syntax error, unexpected keyword_end, expecting end-of-input

删除尾部括号可修复错误:

irb(main):001:0> module Auth
irb(main):002:1>   def login(id)
irb(main):003:2>   end
irb(main):004:1> end
=> :login

irb(main):001:0> module Auth
irb(main):002:1>   module_function()
irb(main):003:1>
irb(main):004:1*   def login(id)
irb(main):005:2>     members = ['abc', 'def', 'ghi']
irb(main):006:2>
irb(main):007:2*     for member in members do
irb(main):008:3*       if (id == member)
irb(main):009:4>         return true
irb(main):010:4>       end
irb(main):011:3>     end
irb(main):012:2>     return false
irb(main):013:2>   end
irb(main):014:1> end
=> :login

您的代码可能更像Ruby:

def login(id)
  ['abc', 'def', 'ghi'].each do |member|
    return true if (id == member)
  end
  return false
end
login('ghi') # => true
login('foo') # => false

可以重构为:

def login(id)
  ['abc', 'def', 'ghi'].any? { |member| (id == member) }
end
login('ghi') # => true
login('foo') # => false

然后到:

def login(id)
  ['abc', 'def', 'ghi'].include?(id)
end
login('ghi') # => true
login('foo') # => false