0

I need to reuse a textfile that is filled with one-liners such:

export NODE_CODE="mio12"

How can I do that in my Ruby program the var is created and assign as it is in the text file?

4
  • Read the file and for each (matching) line create a variable and assign the value. (or maybe put them in a hash) Commented Jul 9, 2022 at 21:03
  • Maybe the question then is how can I create that var name and assign it into that value in dynamically? Commented Jul 9, 2022 at 21:32
  • 1
    Possibly worth reading: stackoverflow.com/questions/16419767/ruby-dynamic-variable-name And the right answer is probably a hash. Commented Jul 9, 2022 at 22:53
  • Is it bash executable script? Commented Jul 9, 2022 at 23:18

2 Answers 2

3

If the file were a Ruby file, you could require it and be able to access the variables after that:

# variables.rb

VAR1 = "variable 1"
VAR2 = 2


# ruby.rb

require "variables"
puts VAR1

If you're not so lucky, you could read the file and then loop through the lines, looking for lines that match your criteria (Rubular is great here) and making use of Ruby's instance_variable_set method. The gsub is to deal with extra quotes when the matcher grabs a variable set as a string.

# variables.txt

export VAR1="variable 1"
export VAR2=2


# ruby.rb

variable_line = Regexp.new('export\s(\w*)=(.*)')
File.readlines("variables.txt").each do |line|
  if match = variable_line.match(line)
    instance_variable_set("@#{match[1].downcase}", match[2].gsub("\"", ""))
  end
end
puts @var1
puts @var2
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That was the answer I was looking. Never heard about the method instance_variable_set
1

Creating a hash from this file can be a fairly simple thing.

For var.txt:

export BLAH=42
export WOOBLE=67
File.readlines("var.txt").each_with_object({}) { |line, h| 
  h[$1] = $2 if line =~ /^ export \s+ (.+?) \s* \= \s* (.+) $/x
}
# => {"BLAH"=>"42", "WOOBLE"=>"67"}

2 Comments

I don't see the line within the loop that simple.
The regular expression looks for an export line, with the name and the value matched as $1 and $2. If the regex matches, and entry is put into the hash.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.