David West
David West

Reputation: 2328

Ruby - Given string with ENV variables how do I get their values

Say I have

str = "DISABLE_THINGY=true -p my_profile"

To get the value of DISABLE_THINGY (true) I can use

str.partition("DISABLE_THINGY=").last.split(' ').first

I do not want to do that.

There must be a library that parses all this for me.

Anybody know some better ways?

Upvotes: 0

Views: 805

Answers (2)

the Tin Man
the Tin Man

Reputation: 160571

The selected answer is way too convoluted to solve such a simple problem. Regular expressions are great, but the more complex they are, the more likely they'll be wrong:

str = "DISABLE_THINGY=true -p my_profile"
str[/\w+=(\w+)/, 1] # => "true"

/\w+=(\w+)/ simply looks for "words" joined by =.

See String's [] method for more information.

If you had a number of assignments and wanted to capture them all, or, wanted to capture the name and value of this one:

str = "DISABLE_THINGY=true -p my_profile"
str.scan(/\w+=\w+/).map { |s| s.split('=') } # => [["DISABLE_THINGY", "true"]]

That returns an array-of-arrays, which can be useful, or, you could convert that to a Hash:

str.scan(/\w+=\w+/).map { |s| s.split('=') }.to_h # => {"DISABLE_THINGY"=>"true"}

and similarly:

str = "DISABLE_THINGY=true FOO=bar -p my_profile"
str.scan(/\w+=\w+/).map { |s| s.split('=') } # => [["DISABLE_THINGY", "true"], ["FOO", "bar"]]
str.scan(/\w+=\w+/).map { |s| s.split('=') }.to_h # => {"DISABLE_THINGY"=>"true", "FOO"=>"bar"}

Upvotes: 2

Lance Whatley
Lance Whatley

Reputation: 2455

Take a look at "Parse command line arguments in a Ruby script".

If all of your arguments don't use a hyphen, you might have to make slight tweaks to the regex used, but this should get you where you need to go. Just replace ARGV.join(' ') in the accepted answer with your str var.

Adjusted the regex in the link provided above to make your use-case work where you combine ENV variables with command line parameters:

args = Hash[ str.scan(/-{0,2}([^=\s]+)(?:[=\s](\S+))?/) ] => {"DISABLE_THINGY"=>"true", "p"=>"my_profile"}

Upvotes: 1

Related Questions