Ruby Bytes

November 7th, 2006 -

Inspired by Cody Lindley’s JavaScript Tidbits, I’ve decided to follow suit. I’ve been wanting to write some small samples of code to share about the depth of the Ruby language.

There has been so much focus on Rails, that Ruby seems to take a back seat at times. So, I’d like to share somethings that Ruby is very known for being able to do in the Rails world. Let’s start with this example of using Ruby scripting power to search within a file.

Open up either your Terminal window (OSX) or your command line (PC) and let’s dive in!

ruby -n -e 'print "LINE #{$.}: #{$_}" if /div/i' public/index.html

The above code is intended to be typed in the Terminal/Command window. It is a basic file search command that will print out the line number and the content of that line if it contains the word “div” in it. The file that it is searching through is the index.html file. Ok, let’s take it apart to better understand it.

ruby -n -e

The “-n” is a while loop that is wrapped around your script and gets what you are asking for. The “-e” is a command or a line of script code to be run.

‘print “LINE #{$.}: #{$_}”

The “print” obviously means to print what is within the quotes, that has been retreived by our script, out to the display. In the quotes, the #{$.} keeps the number of lines read in within it and #{$_} stores the content of those lines found that contain the string “div”.

if /div/i’

This snippet is basically saying if the line contains “div” then it will be printed out with the line number and content. The ”//i” part sets our search to be case insensitive.

public/index.html

As you might have guessed, the above snippet of our script, simply tells our script what file to search in.

There you have it, a very simple example of using Ruby as a scripting language to do a simple search within a file. In the future, I will be posting more little snippets of Ruby code and explanations to show the range of Ruby and that it isn’t just a backing band for Rails.

If you have suggestions, comments, questions, disagreements, or would like me to post a tutorial on some aspect of Ruby/Rails, leave me some feedback here in the comments.

Tags: ruby, ruby bytes

 

Comments

 

Commenting has been turned off.