New Methods in Ruby 2.2

article

#1

Originally published at: http://www.sitepoint.com/new-methods-ruby-2-2/
vector illustration of dark red shield with ruby programming lan

Most of the fanfare around Ruby 2.2 has focused on garbage collection (GC) upgrades. The GC will now clean up symbols and has a new incremental algorithm that reduces the pause time. These changes are very exciting, but there were some new methods added as well. Let’s see what other new toys 2.2 delivered.


Continue reading this article on SitePoint

#2

Hello Aaron,

good article. However you miss "self" for the class method in Binding#receiver example.

class Cat
def type => (must be self.type)
binding.receiver
end
end

Thanks


#3

Ah yes, good catch.


#4

Good stuff, Aaron. The surprise win for me was that you took me on a sidetrack to finally grok the === operator, which I'm embarrassed to say I hadn't really understood until now.


#5

You'll find the slice_* methods used often when parsing text files, such as device configurations, where there are blocks of commands or settings that need to be grouped.

I've written several such device parsers, and slice_before made it almost trivial.


#6

I think there's a typo in the curry setup. You still need an & to call to_proc on :+ and pass it as the block param, right?

def sum(*args)
  args.reduce(&:+)
end

#7

You don't need the & when using reduce. It will accept a symbol and call to_proc for you.


#8

In general, yes. But as of ruby 1.9+, there is a shortcut for Enumerable#inject to only pass a symbol (which is nice, since this is the most common use for the method!).


#9

I can't understand Binding#receiver

I have same result with self:

class Cat
  def self.type
    binding.receiver
  end
end

> Cat.type
Cat

class Tiger < Cat
end

> Tiger.type
Tiger

#10
class Cat
  def self.type
    self
  end
end

#11

In that particular example it's serving the same purpose as self. The difference is that a binding can be passed around.

class A
  def get_binding
    binding
  end
end

> a = A.new
# => #<A:0x007fe9b44cd880>
> b = a.get_binding
# => #<Binding:0x007fe9b44fcfe0>
> b.receiver
# => #<A:0x007fe9b44cd880>

Bindings are a window into a particular scope. Now it's easier to find where that scope came from. Does that help clarify it?


#12

Does that help clarify it?

Yes, than you!


#13

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.