[email protected] wrote:
A few simple syntax questions:
- Anyway to do use the default arg for nonlast params? Something
like:
run(xyz, , 3)
No. You have to use one form of keyword arguments (for example by using
a
hash). Note that proper support for this is likely to happen in Ruby
2.0.
- Veru often I see things like:
a, b = meth()
Is meth returning two objects? Or is it returning one object - like a
tuple or something - which the parser automagically splits into a & b?
What are the rules of using two vars with commas together?
It’s a combination of parallel assignment with multiple return values.
parallel assignment
a,b,c=1,2,3
a,b,c=[1,2,3]
multiple return values
def mu1
return 1,2,3
end
def mu2
[1,2,3]
end
def mu3
return [1,2,3]
end
irb(main):015:0> a,b,c = mu1
=> [1, 2, 3]
irb(main):016:0> a
=> 1
irb(main):017:0> b
=> 2
irb(main):018:0> c
=> 3
irb(main):019:0> a,b,c = mu2
=> [1, 2, 3]
irb(main):020:0> a
=> 1
irb(main):021:0> b
=> 2
irb(main):022:0> c
=> 3
irb(main):023:0> a,b,c = mu3
=> [1, 2, 3]
irb(main):024:0> a
=> 1
irb(main):025:0> b
=> 2
irb(main):026:0> c
=> 3
The star operator can be used to collect remaining args:
irb(main):029:0> a,*b = mu1
=> [1, 2, 3]
irb(main):030:0> a
=> 1
irb(main):031:0> b
=> [2, 3]
More strictly speaking, returning anything that implements #to_ary will
be
treated this way:
irb(main):032:0> class Foo
irb(main):033:1> def to_ary() [“foo”,2,3] end
irb(main):034:1> end
=> nil
irb(main):035:0> def foo() Foo.new end
=> nil
irb(main):036:0> a,b,c = foo
=> [“foo”, 2, 3]
irb(main):037:0> a
=> “foo”
irb(main):038:0> b
=> 2
irb(main):039:0> c
=> 3
HTH
Kind regards
robert