Solved

In ruby, how do I just select lines in a file with the string "free" in them.

Posted on 2010-08-12
3
429 Views
Last Modified: 2012-05-10
I have a data  file:
vette  20K
honda  free
kia  5K

My program:
# ruby file processing, version 1
file='C:\Documents and Settings\My Documents\rubyme.txt'
f = File.open(file, "r")
f.each_line { |line|
      puts line.grep("free")
}
f.close

I made up the command grep but you know what I want.  I just want the lines of the datafile with "free" in them.  
0
Comment
Question by:TIMFOX123
3 Comments
 
LVL 14

Accepted Solution

by:
wesgarrison earned 300 total points
ID: 33426061
Use a regex with =~ to match.
No match will return nil, which is false-y.
puts line if line =~ /free/

Open in new window

0
 
LVL 12

Assisted Solution

by:cminear
cminear earned 200 total points
ID: 33431193
Very similar but more straightforward for your case: try this.
puts line if line.include? 'free'

Open in new window

0
 

Author Closing Comment

by:TIMFOX123
ID: 33432822
this is great !!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Routing in Rails 3 3 680
Ruby on Rails Webrat Error 1 423
Ruby issue 7 286
Create an application - what tools to use? 4 607
In Ruby, Call or invoke a API DLL library is easily via Win32API class, win32-api gem or other gems. For general DLL API call, there are quite a few references, some good tips list below: http://www.rubytips.org/2008/05/13/accessing-windows-api-fro…
Recently I spent hours debugging an issue in a Rails project where ActiveRecord was causing MySQL errors trying to create a User object of a class at the top level of a Single Table Inheritance model structure.  It turns out `.create` behaves differ…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now