Home > Back-end >  How to create a list of variables in ruby?
How to create a list of variables in ruby?

Time:07-02

I’m trying to create something like an inventory in ruby, so I can compare "params" against every line in that inventory, but I’m new to the language and I don’t know what might be the best way to do it.

Actually my code looks like this:

def parseParams(params)
    max_length = "xxxxxxxxxxx".length
    min_length = 2 #c1 for example

    if (params.length == 0)
        puts "[-] No parameters provided"
        return false
    elsif (params.length > max_length)
        puts "[-] The parameters are too long/invalid"
        return false
    elsif (params.length < min_length)
        puts "[-] The parameters are too short/invalid"
        return false
    else
        if (params == "c1" || params == "c2" || params == "c3")
            puts "[ ] Valid parameters"
        return true
        end
    end
end

What I want to do is simplify the code and just verify whether "params" exists in this inventory, otherwise, return error.

Someone knows how to do it?, thanks in advance.

CodePudding user response:

To summarise the requirements of your question:

If params is equal to any line in inventory.txt then it's valid, otherwise it's invalid

You can do this:

def parseParams(params)
  File.read('inventory.txt').split("\n").include?(params)
end
  •  Tags:  
  • ruby
  • Related