DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone >

List Comprehensions In Ruby

Snippets Manager user avatar by
Snippets Manager
·
Jan. 12, 07 · · Code Snippet
Like (0)
Save
Tweet
627 Views

Join the DZone community and get the full member experience.

Join For Free
Taken from: http://www.ruby-forum.com/topic/89416
Author: Phrogz

To avoid reinventing the wheel check out the built-in methods described in:
http://www.ruby-doc.org/core/classes/Array.html and
http://www.ruby-doc.org/core/classes/Enumerable.html.




#class Array 
module Enumerable
  def comprehend(&block) 
    block ? map(&block).compact : self 
  end 
end 


old_data = *(1..5)          # alternatives to the splat operator: (1..5).to_a or (1..5).collect
new_data = *(3..9)


# some reinventing going on here ...
added = new_data.comprehend { |x| x if not old_data.include?(x) } 
removed = old_data.comprehend { |x| x if not new_data.include?(x) } 
same = new_data.comprehend { |x| x if old_data.include?(x) } 
modified = new_data.comprehend { |x| x**2 if not x % 2 == 0 }

p added                                            #=> [6, 7, 8, 9]
p added = new_data - old_data                      #=> [6, 7, 8, 9]

p removed                                         #=> [1, 2]
p removed = old_data - new_data                   #=> [1, 2]

p same                                              #=> [3, 4, 5]
p same = old_data & new_data                        #=> [3, 4, 5]
 
p modified                                        #=> [9, 25, 49, 81]


new_data = [[5, 9], [22, 3], [99, 564]]
bool_vals = new_data.comprehend { |x, y| x <= y }
p bool_vals                                      #=> [true, false, true]


Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Migrating Secrets Using HashiCorp Vault and Safe CLI
  • Debugging Deadlocks and Race Conditions
  • How to Determine if Microservices Architecture Is Right for Your Business?
  • JUnit 5 Tutorial: Nice and Easy [Video]

Comments

Partner Resources

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo