Ezra Zygmuntowicz
12/12/2008 9:48:00 PM
Hi~
On Dec 12, 2008, at 12:58 PM, Matthew Moss wrote:
>
> On Dec 12, 2008, at 2:21 PM, Louis-Philippe wrote:
>
>> Thanks Matthew,
>>
>> "No, because what was provided before wasn't wrong."
>>
>> Yeah... I believe you, but would really like it to be else!
>
>
> Think of it this way...
>
> def foo
> return 1, 2, 3
> end
>
> a = foo
>
> Now, you want a to be 1, but Ruby would need the power to read minds
> to accommodate that. See, because if I do the same, I want a to be
> [1, 2, 3]. How is foo supposed to figure that out? Or why should
> your want be more/less preferable than my want?
>
> Simply, the interpreter can't know. There has to be some syntax or
> something that gives foo, or the assignment to a, that key
> information.
>
> Telling foo would be passing an arg:
>
> def foo(nargs)
> return [1, 2, 3][0...nargs]
> end
>
> a = foo(1)
>
> Any of the other examples come after foo is done, so:
>
> def foo
> return 1, 2, 3
> end
>
> a, = foo
> a = foo[0]
> a = foo.first
>
> All three of those do the same... assign 1 to a. The latter two
> request specifically the first item, while the first does parallel
> assignment (of array components to particular variables... in this
> case, only a). Since you seem interested in parallel assignment to a
> variable number of variables, the first seems appropriate. Granted,
> forgetting the comma might be easy, but there's no way for foo to
> know that you want a = foo to return 1 and that someone else that
> does a = foo wants [1, 2, 3].
you can use the masign commas to get sort of what you want:
irb(main):001:0> def foo
irb(main):002:1> return 1,2,3
irb(main):003:1> end
=> nil
irb(main):004:0> a, = foo
=> [1, 2, 3]
irb(main):005:0> a
=> 1
Cheers-
Ezra Zygmuntowicz
ez@engineyard.com