We Recommend

Beginning Ruby: From Novice to Professional Beginning Ruby: From Novice to Professional
Beginning Ruby is a thoroughly contemporary guide for every type of reader wanting to learn Ruby, from novice programmers to web developers to Ruby newcomers. It starts by explaining the principles behind object-oriented programming and within a few chapters builds toward creating a genuine Ruby application.


Posted By

vanne on 01/23/07


Tagged

ruby


Versions (?)


Just in time convenience methods


Published in: Ruby 


URL: http://toolmantim.com/article/2006/11/29/instance_eval_brings_sexy_back

Using instance_eval to abstract values into meaningful methods

  1. time_components = /(\d+):(\d+):(\d+)/.match("17:00:34")
  2. time_components.instance_eval do
  3. def hours; self[1] end
  4. def minutes; self[2] end
  5. def seconds; self[3] end
  6. end
  7.  
  8. time_components.hours # => "17"
  9. time_components.minutes # => "00"
  10. time_components.seconds # => "34"
  11. time_components.class # => MatchData

Report this snippet 

You need to login to post a comment.