Search code examples
rubyobjecttimestampparameter-passingblock

Ruby: how to pass object to a block and return a calculated value depending on the obj?


I would like to do something similar:

seconds=Time.parse("0:26:29.489").magic{|z| z.hour+z.min+z.sec+z.nsec.fdiv(1_000_000)}

to convert a timestamp into seconds (with fractions too), instead of writing:

d=Time.parse("0:26:29.489")
seconds=d.hour+d.min+d.sec+d.nsec.fdiv(1_000_000)

to spare a temporary "d" variable. But what should I use for "magic" if any?


Solution

  • Ruby has tap, but that won't help you here. What you want is something that would be called pipe, but sadly it's not there. At least not without a gem that monkey patches Object. Though I think it should be.

    You can create a lambda and immediately call it, which will avoid the intermediate variable (or at least contain it within the lambda's block scope, as in your magic example), but I'm not sure you gain much, and would probably stick with what you have. The lambda approach would look like this:

    # will return the value for "seconds"
    ->(d) { d.hour+d.min+d.sec+d.nsec.fdiv(1_000_000) }.(Time.parse("0:26:29.489"))