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

38

u/TikiTDO Feb 24 '13 edited Feb 24 '13
# Ruby 2.0:
def cycle(first_value, *values, name: 'default')
  # ...
end

May I be the first to say, "Holy shit, about time." Also, does anyone have an English translation of the Flonum paper? I'd be really grateful.

14

u/galtthedestroyer Feb 24 '13

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

33

u/lobster_johnson Feb 24 '13 edited Feb 24 '13

Ruby 1.x only has positional arguments with defaults:

def foo(a, b = nil)z
   ...
end

You can call this only with arguments that follow the order specified in the definition:

foo(1)  # now b is nil
foo(1, 2)  # now b is 2

There is also some syntactic sugar to allow a hash table to be appended as the last argument without using braces.

foo(1, x: 42)  # now b is {x: 42}

This syntactic sugar has been very nice, but using a hash table has some drawbacks:

  • Expensive: hash table is built at runtime.

  • Memory-inefficient: hash table must be allocated, and with Ruby objects clocking in at several hundred bytes, it's a lot of unnecessary stuff for something that stays around for a very short while.

  • There is no way to know if the passed-in hash table was a literal or not (if it's a literal then the called method can safely modify it without copying it first, which is faster).

  • There is no way to specify, as part of the method definition, what keys are supported. Therefore, you have to put that in the documentation, and then perform runtime assertions.

  • There is no way to specify defaults for keys. You have to look up the key in the hash table, and then insert a default if it's missing. So you get a lot of "||" or "||=" operations, which are also slow.

  • Promotes laziness, in that devs will let a method take an "options" hash table and then pass it on to other methods, perhaps after modifying it first by adding or deleting keys.

Old style:

def convert(file_name, options = {})
  options.assert_valid_keys(:format, :quality)  # from the "activesupport" gem
  format = options[:format] || 'jpeg'
  converter = SomeKindOfImageConverter.new
  converter.load(file_name)
  return converter.convert(to_format: format, compression: quality)
end

convert("my_image.png", quality: 0.7)
convert("my_image.png", quality: 0.7, foo: 3)  # Caught by assertion
convert("my_image.png", format: "tiff")

New style:

def convert(file_name, format: "jpeg", quality: 0.7)
  converter = SomeKindOfImageConverter.new
  converter.load(file_name)
  return converter.convert(to_format: format, compression: quality)
end

convert("my_image.png", quality: 0.7)
convert("my_image.png", quality: 0.7, foo: 3)  # Caught by Ruby
convert("my_image.png", format: "tiff")

Edit: Apparently Ruby 2.0 implements keyword arguments as a hash table internally, which sucks, and means that my first two bullet points remain. Hopefully the implementation will get better.

11

u/eluvium Feb 24 '13

I was confused by this one, but you've made it much clearer, thanks!

It sounds quite like Python's keyword arguments.

21

u/zeekar Feb 24 '13

That's why they call the new feature in Ruby "keyword arguments".

2

u/eluvium Feb 24 '13

Ha! Yeah, wow. I can't read.

4

u/madmars Feb 24 '13

sounds exactly like what people do in Perl to pass parameters, which is a huge pet peeve of mine:

doSomething( argument => 'whatever' );

Then if someone goofs...

doSomething( argrument => 'whatever' );

Then you're proper fucked. I spend nearly an hour one day, tracking down this stupid bug because someone had a lowercase letter where an uppercase letter should have been. I started making it a point to do:

sub doSomething {
    my @required = qw(required1 required2 ...);
    my @optional = qw(optional1 optional2 ...);
    # check input against both required and optional...
}

However this is tedious, since you have to check...

  • Required parameters. Ensure all of these are passed.

  • Parameters passed which are neither in required or optional

The last check is important, otherwise you won't catch misspellings and parameters that people just assume work with the subroutine but actually do not.

4

u/jplindstrom Feb 24 '13

Nowadays you can use Method::Signatures to get both some nice sugar for unshifting $self, and for declaring a proper parameter list (about time).

So now you can write:

method set (Str $key, Int $val) {
    # now you know $val is always an integer
    return $self->{$key} = $val;
}

with runtime type checking, or

 method deposit(:$amount = 42) {

to declare a named parameter with a default.

(The syntax is pretty much nicked from Perl 6 in the usual let's-steal-cool-shit-from-wherever-we-can-find-it way.)

If that's too high-tech, I recommend MooseX::Params::Validate, which does the job but is a bit noisier syntactically.

2

u/madmars Feb 24 '13

Yeah, I figured CPAN had something. And I did remember Moose having something like that.

CPAN modules like this that affect language semantics are great--if you start using them from day one. You also need strict adherence from all developers. The prior code base I mentioned had these two competing idioms throughout the code:

deposit( amount => 42 );

and

deposit( { amount => 42 } );

They look just similar enough that you'll bang your head every time you need to pass parameters to anything.

Worse still, they tried to modernize their OO code from the old bless hashref style to Moose. So not only did they have two argument passing styles going on, they had two OO styles as well.

This isn't to blame Perl though. C++11 and certainly others are going through this exact same problem, where there is an older style of coding still in use and people desire switching to the new style.

2

u/[deleted] Feb 24 '13

Then if someone goofs...

doSomething( argrument => 'whatever' );

With Ruby 2.0's keyword arguments this would cause an ArgumentError now, because argrument is not a known keyword.

1

u/lobster_johnson Feb 24 '13

I thought Perl had keyword args — or is that just Perl 6? (Isn't Perl 6 the "current" version yet?)

3

u/madmars Feb 24 '13

Perl 6 might. I don't keep up with it. Perl 5 is largely considered "the" Perl, which is what the "modern Perl" movement is based on. If you find any Perl software or any company looking for Perl developers, it's almost certainly going to be version 5.

6 is so different that they should have just picked a new name, rather than use Perl. But that's just my opinion.

0

u/lobster_johnson Feb 24 '13

According to Wikipedia, you're right, and Perl 6 is still in limbo. Too bad; I dislike Perl, but what has happened to it seems unfortunate.

1

u/coolHandLukeSkywalke Feb 26 '13

Wow...I was about to comment on your "then if someone goofs..." because I couldn't find the problem. That is a wicked typo!

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.