Tarek Saied
Tarek Saied

Reputation: 6616

How does method chaining work in Ruby?

How does method chaining work in ruby? As a C# developer, when I see 1.hour.from_now.localtime, I'm not sure what's going on. How does this code work?

<%= 1.hour.from_now.localtime %>

Upvotes: 2

Views: 250

Answers (2)

Mike Manfrin
Mike Manfrin

Reputation: 2762

1 is an object that responds to hour

pry(main)> 1.class
=> Fixnum

.hour is a method on Fixnum that signifies it as an hour (by changing it to 3600)

pry(main)> 1.hour.class
=> Fixnum
pry(main)> 1.hour.to_i
=> 3600

.from_now changes the type of 3600 to a DateTime, 3600 seconds in to the future.

pry(main)> 1.hour.from_now
=> Mon, 22 Sep 2014 19:57:05 UTC +00:00
pry(main)> 1.hour.from_now.class
=> ActiveSupport::TimeWithZone

.localtime changes the TimeZone to the system local time:

pry(main)> 1.hour.from_now.localtime
=> 2014-09-22 12:57:41 -0700

Upvotes: 13

jstim
jstim

Reputation: 2432

Everything in Ruby is an object, so in this case:

  • The Fixnum 1 object receives the message hour
    • Which returns a Fixnum of seconds
  • 3600 seconds receives the message from_now
    • Which returns an ActiveSupport::TimeWithZone object
    • Essentially it offsets the current time (the from_now) by an offset (our initial Fixnum of seconds)
  • This Time object then receives the message localtime

If you want to explore each step, you can use the rails console and evaluate each step to see the return value (and call class on each step to see how it changes the type)

Upvotes: 5

Related Questions