1

I am trying to perform the following operation.

@i, price_0, price_1, price_2 = 0, 0, 0, 0
   until @i > 2 do
     if trade_history[@i]["type"] == 2
       price_"#{@i}" = (trade_history[@i]["xbt_gbp"]).to_f ##NOT WORKING
     end
     @i += 1;
   end

I cannot find anywhere online where it says that you can dynamically name a variable in Ruby. What I want to be able to do is to extract the prices of the trade_history object whenever they have a type 2. I need to be able to use the prices variables (price_0..2) to make calculations at the end of the loop. Please help! :-)

mageofzema
  • 85
  • 7

2 Answers2

0

I do not think this is the best way to do it, you should rather use a Hash containing the prices, but if you really want to dynamically assign the local variables you created, use binding.local_variable_set.

binding.local_variable_set("price_#{@i}", "your value")

Note that this is only available from Ruby 2.1. See How to dynamically create a local variable? for more info.

If you prefer an instance variable, you can use.

instance_variable_set("@price_#{@i}", 1)
Community
  • 1
  • 1
Daniel Perez
  • 6,335
  • 4
  • 24
  • 28
  • Note that `Binding#local_variable_set` will only create a local variable *inside* the `Binding` object, *not* in the scope from which the `Binding` was created. In this case, it doesn't matter, because you don't *have* to create the variable, it is already created in line 1, you only have to *set* it which works perfectly fine. But I think your first sentence is a bit misleading this way. Yes, you can create variables, but they won't be created where you think they will be, and if the OP hadn't already created the variable in line 1, your suggestion wouldn't work. – Jörg W Mittag May 24 '15 at 09:20
  • Thanks, I updated my answer to avoid any confusion. – Daniel Perez May 24 '15 at 09:47
  • Thank you, this was helfpul :-) – mageofzema May 26 '15 at 14:55
0

Just store the values in an array:

prices = []
3.times do |i|
  history = trade_history[i]
  prices << history["xbt_gbp"].to_f if history["type"] == 2
end

After this loop the prices array would hold the results and look like this:

prices    
#=> e.q. [0.2, 0.4, 0.5] 

Calculations can be easily done with reduce or inject:

prices.inject(:+)
#=> 1.1
spickermann
  • 100,941
  • 9
  • 101
  • 131
  • Thank you :) This worked like a charm. initially I was testing it in PRY and it appears that they have a command called history which confused things a bit for me. – mageofzema May 26 '15 at 14:55