Search code examples
rubyhighline

Highline ruby gem. How to provide a variable number of menu choices at runtime


My first ever stack overflow post. I am supposed to be succinct and to the point, but please indulge me in some background the first time around. I have been programming in C and Visual Basic for 16 years, but only part time to support my work as a scientist. Started learning ruby about a year ago and really enjoy it. I am writing a program that processes data. This works with folders and files rather than a database. Every time I get stuck, I can always find a solution here (what a great resource!) or on Google. This time is different. So to the point:

I want to use the highline gem in ruby to display a menu with a variable number of menu items. Essentially I want the user to select a directory. There could be any number of directories in the parent directory. My code is as follows:

@allArchiveDirs =  Dir.entries(@dirArchive).select {|entry| File.directory? File.join(@dirArchive,entry) and !(entry =='.' || entry == '..') }
p @allArchiveDirs

choose do |menu|
  menu.prompt = 'Please choose a project to access:'
  temp = @allArchiveDirs.map &:to_sym
  # todo here. Cannot get temp into correct format for choices call.
  temp = temp.map{|x| x.inspect}.join(', ')
  p temp
  menu.choices(:old1, :old5) do |chosen|
    puts "Item chosen: #{chosen}"
  end
end

In parenthesis for the menu.choices call I would normally have temp, but currently I have :old1, :old5 just for my own debugging purposes or I get an error.

The output is:

["deletemetest", "old2", "old3", "old4", "TestData", "testy123", "tsty"]

":deletemetest, :old2, :old3, :old4, :TestData, :testy123, :tsty"

  1. old1
  2. old5

Please choose a project to access:

So the symbols seem to be a string (on account of the quotes around it). If I can remove these I may succeed in getting temp into the correct format for the menu.choice call.


Solution

  • You actually don't need to do all this type conversion, all you need is the splat operator

    @allArchiveDirs = ["deletemetest", "old2", "old3", "old4", "TestData", "testy123", "tsty"]
    choose do |menu|
      menu.prompt = 'Please choose a project to access:'
       menu.choices(*@allArchiveDirs) do |chosen|
        puts "Item chosen: #{chosen}"
      end
    end
    

    Output:

    1. deletemetest
    2. old2
    3. old3
    4. old4
    5. TestData
    6. testy123
    7. tsty
    Please choose a project to access: