Kimberly Wright
Kimberly Wright

Reputation: 531

Parse a Ruby Variable inside YML file

I have a yml file here where I took a part of my ruby code and make it a hash:

answer: "The answer is: #{result}"

The result variable is from my ruby code where I initiated here:

require 'yaml'
MESSAGES = YAML.load_file('mymessages.yml')

result = case operator
           when '1'
             number1.to_i() + number2.to_i()
           when '2'
             number1.to_i() - number2.to_i()
           when '3'
             number1.to_i() * number2.to_i()
           else
             number1.to_f() / number2.to_f()
           end

  prompt('answer')

When I initiated this, it's just displaying the whole text as a string but the result variable was not displayed w/c is suppose to be an addition or subtraction etc. of 2 numbers.

Do you know how to fix this?

Thanks!

Upvotes: 1

Views: 1377

Answers (2)

peter
peter

Reputation: 42192

You need to extract the piece of code you have a problem with in a separate script that you can test or publish on its own, here an example of what I made of your code, I must guess at the contents of your Yaml file since you didn't provide that.

require 'yaml'

MESSAGES = YAML.load_file('./mymessages.yml')
p MESSAGES # poor mans debug
operator = MESSAGES["operator"].to_f #supposing in your yaml it is a Hash with key "operator"
#operator = '1' # for testing without the yaml
number1, number2 = 4.0, 5.0

result = case operator
when '1'
  number1 + number2
when '2'
  number1 - number2
when '3'
  number1 * number2
else
  number1 / number2
end

puts result # 9.0
prompt = "The answer is: #{result}".sub(/\.0$/,'') #remove unwanted traling .0
puts prompt # The answer is: 9

You see I use variables that I can check wit a puts or p, real testing would be better but I don't have time to explain all that, but you should learn it. If you do things more than once like the .to_i conversion try to save that in a variable. Also I don't see the need to work with both integers ands floats, if one is float, treat them all like float and if you don't want the traling zero remove it with the sub method or chaneg the type once like this

result = result.to_i if result == result.to_i

Upvotes: 0

Jörg W Mittag
Jörg W Mittag

Reputation: 369458

YAML and Ruby are two different languages. You can't use Ruby string interpolation in YAML, because YAML is YAML, not Ruby. You can only use Ruby string interpolation in Ruby.

Upvotes: 1

Related Questions