Solved

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

Posted on 2010-08-12
3
439 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

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I recently rediscovered rails when I needed a holiday project and decided to build a management dashboard for the company where I work.  With it being a project done in my free time, I could focus my time on learning the basics rather than trying to…
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…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 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