-1

Using IRB, I tested the following:

C:\Pickaxe>irb
irb(main):001:0> list_of_strings = %w{ a list of strings in an array }
=> ["a", "list", "of", "strings", "in", "an", "array"]
irb(main):002:0> a, b, c = list_of_strings
=> ["a", "list", "of", "strings", "in", "an", "array"]
irb(main):003:0> a
=> "a"
irb(main):004:0> b
=> "list"
irb(main):005:0> c
=> "of"
irb(main):006:0>

In the other languages I've developed in setting a, b, c = d sets the values of a, b and c to equal d in its entirety. Here they are set to successive elements in the array.

I don't understand how or why this works. Could someone shed light on the issue?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Senjai
  • 1,811
  • 3
  • 20
  • 40
  • 1
    Take a look at [this](http://stackoverflow.com/questions/2895957/parallel-assignment-operator-in-ruby) answer. – squiguy May 14 '13 at 22:41
  • 1
    Ahh, thank you Squiguy. Is there a way I could assign the values of a, b, and c to the whole array without having to do it on multiple lines? – Senjai May 14 '13 at 22:44
  • 3
    Do you mean something like `a = b = c = list_of_strings`? – squiguy May 14 '13 at 22:56
  • Ahh, see that'd work :) Thanks – Senjai May 14 '13 at 23:02
  • Ruby is a little different. I mean the language always brags that it does "what makes sense to the programmer." – squiguy May 14 '13 at 23:06
  • 2
    @squiguy: Destructuring bind in Ruby works pretty much exactly how it works in every other language. Not sure what's so different about that. – Jörg W Mittag May 15 '13 at 00:31
  • 1
    @squiguy, "I mean the language always brags that it does 'what makes sense to the programmer.'" Matz, says "[The principle of least surprise means principle of least my surprise. And it means the principle of least surprise after you learn Ruby very well.](http://www.artima.com/intv/rubyP.html)" Personally, after many other languages, I find Ruby to be very intuitive *when* I stop to think about what I'm doing. Being human I sometimes *don't* do that, which is when I am surprised. – the Tin Man May 15 '13 at 01:35
  • Why was this question downvoted? Am I not asking questions properly? :/ – Senjai May 15 '13 at 03:02

1 Answers1

1

That's just how array assignment works in Ruby. It's trying to be clever, a little, by assigning each indexed item of the array to that variable on the left-hand side of the assignment =

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Alex Mcp
  • 19,037
  • 12
  • 60
  • 93
  • I'm not sure why this would be surprising. Perl does the same thing, and it's been around for years and years, and it's very much a mainstream language. – the Tin Man May 15 '13 at 01:45