r/programming • • Feb 24 '13

Ruby 2.0.0

http://www.ruby-lang.org/en/news/2013/02/24/ruby-2-0-0-p0-is-released/
600 Upvotes

193 comments sorted by

View all comments

Show parent comments

14

u/galtthedestroyer Feb 24 '13

How is that different than before? ( yes I'm new. )

5

u/TikiTDO Feb 24 '13

Previously the closest you could get to this behaviour was:

def cycle(first_value, *values, options)
  name = options[:name] || 'default'
end

In fact, you would not actually use a function like this due to problematic varargs. The above function would fail if you do not pass any options since a call like cycle(1, 2) would set "first_value = 1", and "options = 2". This would then cause an exception on the next line.

As such, in reality you would probably see something along the lines of:

def cycle(first_value, opt_value = nil, opt_value_2 = nil, options = {})
  name = options[:name] || 'default'
  # ...
end

As you may imagine, this sucked for readability (particularly in documentation, where people would not describe the options a function accepted), was a lot more verbose, and generally ended up being quite annoying.

1

u/epochwolf Feb 24 '13

This is how I do it.

 def cycle(*values, options={})
   options = {name: 'default'}.merge(options)
   #...
 end

1

u/TikiTDO Feb 25 '13

That's giving me a syntax error in ruby 1.9.3. As far as I know you couldn't have a normal optional parameter after a vararg.