Sign in to follow this  
steved3298

Tab completion for Console

Recommended Posts

Hi, I am making a game using Ruby and have written my own console library, but when trying to get tab-completion to work it is not perfect and sometimes it does not tab-complete the right commands. The code for my tab completion is:
def tabComplete()
   cmds = findCommands().sort
	
   @tab = @buffer if @buffer[0..@tab.length - 1] != @tab # To allow for multiple commands
		
   cmds.each do |cmd|
      if cmd[0..@tab.length - 1] == @tab
         if @buffer != cmd
	    @buffer = cmd
	    cursorEnd()
	    break
	  end
      end
   end
end

Most of this is self-explanatory with findCommands().sort returning all the commands sorted alphabetically and @buffer being the line buffer. If someone could help me out that would be greatly appreciated. Thanks, Steve

Share this post


Link to post
Share on other sites
I'm not sure. All that find commands does is return all user commands
return Console.protected_instance_methods(false)


Tab-completion works, just not as well as I would like it to. If there are three commands "rcon, rcon_password, respawn" and I type "r"-tab it only cycles through "rcon, rcon_password" instead of all of them. And then if I delete all that and only put in "re" and press tab is goes to "rcon". I am pretty sure it is a problem with
@tab = @buffer if @buffer[0..@tab.length - 1] != @tab

Share this post


Link to post
Share on other sites
You're failing to take full advantage of Ruby. This looks like C++ code, no good! Here's how you can do this _much_ more cleanly in Ruby.


#!/usr/bin/env ruby

class String
def starts_with? str
self[0..str.length-1] == str
end
end

commands = %w{ rcon rcon_console restart }
while b = gets.chomp
e = commands.find {|i| i.starts_with? b}
puts "Expanded command: " + e
end

Share this post


Link to post
Share on other sites
Quote:
Original post by jonahrowley
You're failing to take full advantage of Ruby. This looks like C++ code, no good! Here's how you can do this _much_ more cleanly in Ruby.


#!/usr/bin/env ruby

class String
def starts_with? str
self[0..str.length-1] == str
end
end

commands = %w{ rcon rcon_console restart }
while b = gets.chomp
e = commands.find {|i| i.starts_with? b}
puts "Expanded command: " + e
end

Very cool, thanks very much. There always seems to be an easier way with Ruby.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this