使用Ruby中的Readline以@(at符号)开头的自动完成字符串

时间:2010-11-03 02:52:50

标签: ruby readline

嘿伙计们,如果我有这样的选项,我一直在努力完成自动完成和readline:

["@lorem", "@ipsum", "#bla", "#meh"]

我在提示符中输入@(在符号处)并按TAB键显示所有选项:

what do you want? > @[TAB] 
@lorem @ipsum #bla #meh

但如果我使用任何其他标志,它会起作用:

what do you want? > #[TAB]
#bla #meh

这是我到目前为止的代码:

  opts = ["@lorem", "@ipsum", "#bla", "#meh"]
  question = "whatever? > "

  Readline.completion_append_character = " "
  Readline.completion_proc = proc { |s| opts.grep( /^#{Regexp.escape(s)}/ ) }

  while value = Readline.readline(question, true)
      exit if value == 'q'
      puts value.chomp.strip
  end
end

有人知道我怎么能让Readline知道@的?

1 个答案:

答案 0 :(得分:3)

这是由@符号包含在readline识别的分词符号列表中引起的。

您可以从分词符号列表中删除@符号,然后这将有效。

opts = ["@lorem", "@ipsum", "#bla", "#meh"]
question = "whatever? > "

Readline.basic_word_break_characters = 
    Readline.basic_word_break_characters.delete("@")
Readline.completion_append_character = " "
Readline.completion_proc = proc { |s| opts.grep( /^#{Regexp.escape(s)}/ ) } 

while value = Readline.readline(question, true)
    exit if value == 'q'
    puts value.chomp.strip
end

运行结果如下: -

whatever? > #(TAB)
#bla  #meh  
whatever? > @(TAB)
@lorem  @ipsum  
whatever? > q