-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?

8
  • 1
    Take a look at this answer. Commented May 14, 2013 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? Commented May 14, 2013 at 22:44
  • 3
    Do you mean something like a = b = c = list_of_strings? Commented May 14, 2013 at 22:56
  • 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. Commented May 15, 2013 at 0: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." 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. Commented May 15, 2013 at 1:35

1 Answer 1

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 =

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.