irb: Learning Ruby Quick

In my previous post I introduced the idea of using irb as a desktop calculator. If you are new to Ruby, however, using irb can have the side effect of teaching you Ruby. Everything you type in irb is a Ruby statement. The response you get from irb is the value Ruby returns from the evaluation of the statement you type. You can use this to try things out in Ruby to see how it behaves. Here is an example exploring how a Ruby Array handles some given Range objects as arguments to the “indexing” method []:

irb(main):001:0> a = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]
irb(main):002:0> a[1..-1]
=> [2, 3, 4, 5]
irb(main):003:0> a[1..a.size]
=> [2, 3, 4, 5]
irb(main):004:0> a[1...-1]
=> [2, 3, 4]

Now we just saw first hand some of how we manipulate Arrays in Ruby. But what if we are curious about what else we can do with an Array? It would be really nice if we could quickly get a list of methods available for my Array. Oh, but we can! Every Ruby object has a methods method that returns an Array populated with the names all the messages it responds to.

irb(main):005:0> a.methods
=> ["select", "[]=", "inspect", "compact", "<<", "&", "clone", 
"method", ... (over 100 other methods) ..., "unshift",
"sort_by", "to_yaml_properties", "fill", "max", "is_a?",
"uniq!", "[]"]

Oh, that is a lot of methods! My version of Ruby/irb returned 128 methods for the object, and they are hard to read all mixed up like that. Good thing we can sort them, too:

irb(main):006:0> a.methods.sort
=> ["&", "*", "+", "-", "<<", "<=>", "==", "===", ... (over 100 
other methods) ..., "uniq", "uniq!", "unshift", "untaint",
"values_at", "yaml_initialize", "zip", "|"]

By scanning the methods available to an object you can get an idea of what you can do with it before you even look at proper documentation (which you want to have handy, too). Using the methods method from irb is also a fast way to recall the name of a method if you forget it and your text editor or IDE does not help you figure it out. I sometimes just try out methods unknown to me just to see what happens, and then I check the documentation shortly thereafter to ensure I understand it.

The most important aspect of irb that enabled me to learn Ruby and keep up with changes in the language was the ability to vet out short bits of code before putting them into a program. For example, if I need to ensure a complicated regular expression will match what I want it to, I can do the initial testing in irb. Then those tests done in irb that supply confidence that the regular expression is correct are copied into the unit tests. Here is a simple example to illustrate the idea:

irb(main):007:0> 'foo bar baz' =~ /\/
=> nil

Oops! I expected an Integer result, which would denote there was a match. However, I forgot I was working in Ruby instead of an old version of grep, and the notations denoting a word boundary in regular expressions are different between the two. It is easily fixed:

irb(main):008:0> 'foo bar baz' =~ /\bbar\b/
=> 4

One other trick I employ in irb is to get a list of currently loaded classes, at least as defined at the top level (i.e. a class within a class or module, like Net::HTTP, will not show up, but Net will and then one could drill down from there). This can be done because every class can be identified by a constant value, and a list of these constants can be obtained from the Object class using the constants class method:

irb(main):009:0> Object.constants.sort
=> ["ARGF", "ARGV", "ArgumentError", "Array", "BasicSocket", 
"Bignum", "Binding", "Buffering", ... (over 100 other entries)
..., "UNIXserver", "UNIXsocket", "URI", "UnboundMethod",
"VERSION", "YAML", "ZeroDivisionError", "Zlib"]

Not all of the entries returned are classes (e.g. ARGF and ARGV), but it does not hurt to know about the other defined constants, too.

With irb at my disposal learning Ruby was a snap, and it was very fun. If you have not yet had the pleasure of learning Ruby then perhaps irb can make your journey more fun, too. Let me know if you try it out!

irb: The New Desktop Calculator

One of the things I love about Ruby is that it comes with irb. It is short for Interactive Ruby, and it is a command line tool to interact with an instance of the Ruby interpreter. To start it up just run irb from the command line (Interactive Ruby is a menu option in the most common Windows Ruby package). One of my most frequent uses of irb is as a calculator:

irb(main):001:0> 1465 + 1723
=> 3188

Simple addition is not too exciting, but that’s just the beginning. When Ruby is at your fingertips, the sky is the limit (limited by your imagination, of course). You can sum up a whole list of numbers quickly:

irb(main):002:0> [1, 2, 3, 4, 5, 6].inject(0) { |x, y| x + y }
=> 21

Use variables to store values or add to them:

irb(main):003:0> a = 515
=> 515
irb(main):004:0> a += 23
=> 538

Or perhaps you need a special function to crunch your numbers today? Just define it, possibly as an instance method for the Array or Integer classes, and then have a blast with it:

irb(main):005:0> class Array
irb(main):006:1>   def sum_of_squares
irb(main):007:2>     inject(0) { |s, x| s + x * x }
irb(main):008:2>   end
irb(main):009:1> end
=> nil
irb(main):010:0> [1, 2, 3, 4, 5, 6].sum_of_squares
=> 91

Take advantage of some mathematical constants! They are available, too, using the Ruby constants shown below.

irb(main):011:0> Math::PI
=> 3.14159265358979
irb(main):012:0> Math::E
=> 2.71828182845905

Finally, there is just one thing to note. If you are doing division and want a decimal point in your results then you need to make sure you are using at least one floating point precision number in your statement (otherwise the result is an integer dividend):

irb(main):013:0> 2352.0 / 17
=> 138.352941176471
irb(main):014:0> 2352 / 17
=> 138

Using irb as a desktop calculator is really just scratching the surface of what one can do, but I think it is a rather cool application of it. If you have never used irb, or even Ruby, go ahead and give it a try! I hope you find it just as useful as I do.

Internal Machine Security

Sorry for the delay in posts here, but I have been sick the past week, and getting back into my regular routine has been challenging since. Also, rather that just post random musings of the day like many other blogs, I try to provide useful original content based on my experience.

However, today I will do as many other blogs do and point to some interesting content from elsewhere that I recently came across. There are two recent articles by Nate Lawson that are very interesting; you may find them here and here, and I suggest you read them. They discuss the security of internal system components—hardware security.

As security practitioners continue to struggle with networks and applications, we still have the same issues affecting components of our hardware. The exact same issues, in fact: authorization, authentication, and security versus performance to name a few. I smile at the thought of a conference room somewhere in the bowels of Intel or AMD where engineers and managers discuss threat models and risk equations and make decisions on what to implement and how to implement PC hardware features based on costs and risks in a manner no different than how a web application’s security is discussed at a software company.

Answers to the Redirection Puzzle

This post discusses answers to the Redirection Puzzle. Do not read on if you do not want to see or discuss answers (yet). :)

Read the rest of this entry »

Redirection Puzzle

Today’s entry here at cosine.org is a little Unix puzzle for everyone to work. I came up with this seven years ago when I was first reading about the Plan 9 shell, rc. Plan 9’s shell has a nifty little syntax for connecting a pipe from an arbitrary file descriptor of one process to any file descriptor of another process when they are invoked at the command line together. Using this syntax we can pipe standard error to a different process than we pipe standard output to:

; {puzzle2000 | tee out.log} |[2] tee err.log
This is standard output
This is standard error
; cat out.log
This is standard output
; cat err.log
This is standard error

As seen above, the puzzle2000 script outputs two lines. It outputs “This is standard output” to standard output and “This is standard error” to standard error. The challenge is repeating the above Plan 9 shell functionality using the Bourne shell instead. Back in 2000 it took me about two weeks of throwing ideas around to work out a solution. This is non-trivial because the Bourne shell’s pipe syntax can only connect the pipe from standard output of the first process to standard input of the second. So can you figure out how to extend this functionality? Give it a try!

Please do not post answers or spoilers in the comments of this post. I have set up an additional post to discuss possible answers and to avoid spoiling it for those that want to work out the challenge. I have also provided a little bit of information about my own solution there, and will eventually update that post with the solution itself. Feel free to post your answers in the comments there (do not read them if you do not want to be spoiled!). Also, if you do not want to register for an account you can email your answers or questions to cosine at cosine dot org, and I will post them if they are good (that is, if they would contribute to a positive discussion) even if they are not correct.

Note that I will delete comments below if they are a spoiler or if they discuss possible answers, so please limit the discussion here to clarification about what the challenge is or other general comments.