Home > front end >  How can I get a Ruby variable from a line read from a file?
How can I get a Ruby variable from a line read from a file?

Time:07-12

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?

CodePudding user response:

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

CodePudding user response:

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"}
  •  Tags:  
  • ruby
  • Related