2

Thank you for taking the time to review and perhaps advise on my simple question. I'm seeking a solution for an exercise on which I'm working.

I'd like to know how to write the contents of this array:

@points = [1, 2, 3, 4]

to this string:

saved_points1  = "SAVED_POINTS2 = [%s]" % [@points]

so that when saved_points1 is printed, it prints:

"SAVED_POINTS2 = [1, 2, 3, 4]"

Right now, I'm seeing this when printed:

"SAVED_POINTS2 = [1234]"

I have a feeling that perhaps this might be a ruby version issue. I'm on 1.8.7. Perhaps if I was on 1.9.x the array would print as expected? Or is there a different/better way to save, read, then print this operation?

In case it makes a difference, SAVED_POINTS2 lives within a module that I require at instantiation. I'm using the variables within that module to load/save the values for my new class (in which @points lives). I bet this isn't the right way to save state, but it's the only way I know how to do it at my current level of ruby comprehension. So, I'm not necessarily looking for advice on a better way to save state, because I want to make sure I understand how to properly read/write from these arrays first. But if you got advice you think I'd understand, I'd love to hear it.

Alexandre Lavoie
  • 8,711
  • 3
  • 31
  • 72
user2448377
  • 69
  • 1
  • 6

2 Answers2

6

Array#to_s does indeed have different behaviour in ruby 1.8 and 1.9. There's universal way to get the string that you want. Array has a join method that concatenates all elements of the array with a separator. Your separator would be a string ', '.

@points = [1, 2, 3, 4]

s = "SAVED_POINTS2 = [#{@points.join(', ')}]"

s # => "SAVED_POINTS2 = [1, 2, 3, 4]"
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
2

If you use the method inspect, it will work well in all ruby versions:

"SAVED_POINTS2 = %s" % @points.inspect
 # => "SAVED_POINTS2 = [1, 2, 3, 4]"
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
fotanus
  • 19,618
  • 13
  • 77
  • 111