Proc and Lambda and Block (oh my)

Something neat about  ruby is the equivalence of procs, lambdas and blocks. Take a quick look here:

foo = Proc.new do |x|
puts "In a proc. X is valued at #{x}"
end
foo.call(24)
output -- "In a proc. X is valued at 24"

Pretty simple. Much like an UnboundMethod object, you have to call the proc with call. It can have variables supplied to it with the slide operator ||, or it can inherit the same from the surrounding scope:

x = 1
foo = Proc.new do
puts "In a proc. X is valued at #{x}"
x = 25
end
puts "#{x}"
-- outputs 25

A lambda is an alternative proc syntax. Instead of explicitly creating a proc object, you get an anonymous one still bound to a variable:

bar = lambda { |x| puts "In a lambda. X is valued at #{x}"}
bar.call(32)
--- output "In a lambda. X is valued at 32"

Now, let’s take a look at a block. First, we define a method that yields to a block:

def runnable
puts "Inside runnable."
yield
puts "Still inside runnable."
end

 

Now, we call the method with the same “do” keyword we already used for the proc:

runnable do
puts "I am a block."
end
--output: Inside runnable.
I am a block.
Still inside runnable.

Much as you can insert Proc.call anywhere inside a scope, so you can also insert yield inside a scope and define the proc on-the-fly in a block. Compare the syntax of yielding a variable to that of using a variable with a Proc:

def runnable
puts "Inside runnable."
yield(42)
puts "Still inside runnable."
end
runnable do |x|
puts "#{x}"
end
output -- 42

This allows an associated block to use a variable set within the method. What’s neat, though, is that we can see that the method that yields has a key difference to a Proc: it cannot see into the external scope:

x = 1
def runnable
puts "Inside runnable."
yield(x)
puts "Still inside runnable."
end
runnable do
puts "I am a block."
end
--output - this code fails with an error.

There’s a scope defined by the method, and the variable x is different inside that method than outside of it. 

All this is documented in a github repo: https://github.com/jamandbees/proclambda — feel free to look through the history and goof around.

conway update

I got half way into Conway and haven’t picked it back up yet. 

The first problem conceptually as that I was stuck thinking about coordinates and coordinates and how does a cell know it has a neighbour and coordinates and neighbours?!

The solution came to me while I was on the bus, going down a beautiful canyon. The cell is a class. It cares about how many neighbours it has, so that it knows whether it is alive, dead or unchanged. 

The world tracks the position of the cells. The information the cell needs is how many neighbours it has. Not its own position, not how big the world is.

I need to write  a world for my cells to live in. Then I’d like something to output graphical information to. I think an ncurses UI would be fine first.

I should upload this to github or something.

 

 

Ideas Ideas Ideas.

Well, daily coding failed as a project. I don’t know whether it’s a discipline issue, or an interest issue, but trying to come up with artificial ways to keep progressing skill can be hard.

 

I’m updating my freebsd vm. I like keeping it around as a standard platform for writing ruby and for testing my code on. If it works on mac os, deploy to FreeBSD and verify it still works. If it does, yay! Whilst doing this, I’ve been trying to come up with a program-y project.

I have a couple of ideas that I’m batting around. Log parsing, message passing over a socket, having worker drones which report back to a central reporting facility. Solved problems, sure, but ones I’m interested in solving myself. Thinking about old problems that I want to re-solve, it hit me that I can write Conway’s game of life.

The rule set isn’t hard to implement, but I’d like to have a UI element too. This means either implementing a command line output with ncurses or whatever, or bringing up a window and drawing to it. Both of which seem very cool. I may even try both.

This seems like a good idea somehow.

Fewer, More Flexible, Options

I had a weird situation at work today. I have a script which runs for a specific amount of time:

script.rb --time 360

I had to add an option to make it run, then sleep, then run, then sleep, and so on. But I also still had to support the total time option.

The first thing I did was come up with a working model inside the code to support “run, then sleep, then run, then sleep”. I decided on a multidimensional array:

timeArray = [[100, 200], [150,300], [10,30]]

And I iterated over each:

timeArray.each do |timeArray|
timeToRun = timeArray[0]
timeToSleep = timeArray[1]
end

Now that was out of the way, I came up with comma-separated-semicolon-delimited strings as a way of specifying this on the command line:

script.rb --runandsleep 100,200;150,300;10,30

I called split on a semicolon first to give me a bunch of arrays containing each comma delimited string, then split on the comma and cast to integers using .to_i:

timesToRun = runAndSleepArgument.split(";")
timesToRun.each do |runAndSleepString|
sleepAndRunTimes = runAndSleepString.split(",")
runTime = sleepAndRunString[0].to_i
sleepTime = sleepAndRunString[1].to_i

All’s well and good, but what if the combination of run and sleep are specified with the total run time?

script.rb --time 150 --runandsleep "30,30;60,60;90,90"

I flopped back and forth for a while. I could preparse the –runandsleep time and if it was greater than the –time then refuse to run. That’d solve it. I could just run for the greater of the two times.

But what if someone enters:

script.rb --time 10000 --runandsleep "30,30"

I could run for 30, sleep for 30, then run for 9940. That had a decent solution.

The problem in my mind here is that I know what these kinds of things are like. I added a command line flag to this script (which is used a lot) called –destroy, because it called the destroyAllHumans function which reset a database. Within a week, the developers and QA were talking about how they were running with DESTROY or not with DESTROY and how it impacted things. As such, I know that the flags enter peoples’ heads. They get inside.

If the flag is non-intuitive, the person using the script is irritated. If the flag is intuitive, the person using the script thinks in terms of the flag.

So I solved the problem thus. You can specify:

script.rb --time 300

or you can specify:

script.rb --time "100,50;100,30;10,100"

Both of the syntaxes really specify a total run time, so why make them different? The script becomes better because it has fewer, more flexible, options.

Ruby 1.9.3 on Mac OS X Lion with XCode 4.3

I wanted to install rails 3.2.4 on Mac OS 10.7. The system ruby is 1.8, but I wanted to run against 1.9.3, and it was tricky getting everything working with XCode 4.3.

I wanted to use RVM, but right now RVM spits out an error telling you that 1.9.3 is kind of covered with XCode 4.3, that prior versions of ruby aren’t supported with 4.3, and that you might want to install OSX-GCC-Installer and remove XCode. If you want to go down that path, the OSX-GCC dude seems like a nice bloke: http://kennethreitz.com/xcode-gcc-and-homebrew.html

I didn’t! As such, I decided to see if homebrew would install ruby 1.9.3 (it does) and how hard it would be to switch between its version of ruby and the system ruby (it’s trivial).

  • Remove rvm if you’ve installed it:
    rm -Rf ~/.rvm
  • Install XCode 4.3 from the app store.
    Once installed, open XCode -> Preferences -> Downloads -> Command Line Tools. Download ’em.
  • Install HomeBrew: http://mxcl.github.com/homebrew/. Do your best with their post-install instructions. I especially found it useful to uninstall macports http://guide.macports.org/chunked/installing.macports.uninstalling.html
  • Install ruby 1.9.3: brew install ruby
  • Open .profile (or .bashrc or whatever bash config file you’re using) and add
    PREPATH=$PATH
    #homebrew suggests putting usr/local/bin before /usr/bin
    export PATH=/usr/local/bin:$HOME/.gems/bin:$PATH
    alias unbrew="export PATH=${PREPATH}"
    

    Now, if you want to use the system ruby you run unbrew from the command line

no main manifest attribute in maven jar

Maven have a pretty awesome tutorial in their getting started guide here: http://maven.apache.org/guides/getting-started/index.html

The problem is that if you follow it letter for letter, then run:

java -jar target/<jarname.jar>

you receive a “no main manifest attribute” error.

Stackoverflow has a good answer for this problem, but it took a few readings before I understood what they were saying. Here’s a link to the stackoverflow question:

http://stackoverflow.com/questions/574594/how-can-i-create-an-executable-jar-with-dependencies-using-maven

Open your pom.xml and add the section listed:

<build>
   <plugins>
      <plugin>
          <artifactId>maven-assembly-plugin</artifactId>
          <configuration>
          <archive>
               <manifest>
                    <mainClass>fully.qualified.MainClass</mainClass>
               </manifest>
          </archive>
     <descriptorRefs>
          <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
 </configuration>
</plugin>
</plugins>
</build>

This goes after the URL tag, but before the dependencies tag.

After this, run the following maven command:

mvn clean compile assembly:single

This will output a jar-with-dependencies.jar file in your target\ directory.

 

Useful Bash date Command

Most every time I write a shell script with bash, I need a date in there somewhere. And most every time, I need to read the man page to work out what the heck the format is I like. Now it’s documented here:

date ‘+%b_%d_%H%M’

This outputs as Name Of Month_Today’s Date_The 24 hour clock time right now.

It’s useful to enclose in backticks:

df -h | mail -s “The disk usage at: `date ‘+%b_%d_%H%M’`” jam@jamandbees.net

 

 

 

What Is Good Documentation?

I’ve been thinking a lot for the last few days about technical documentation, the notes that we keep as developers.

I’m in the habit of keeping documentation for the current state of the system. That’s always seemed reasonable to me. Whatever version has just been released, that’s documented well and that has always seemed reasonable and good to me.

Now, though, I’m thinking about how when I’m handing a system over to someone else the documentation they want is how the system evolved during development. The “what happened in the past” part of this is captured in version control. The “why were these decisions made” part is not, and that’s a useful piece of the puzzle for anyone who has to maintain someone else’s codebase.

I document the “how to use this” for each stable release of a codebase. I have never written down the “Why I made this decision” bit of things. When I think of how many times I’ve worked on someone else’s piece of code and the details of why this is the implementation became clear because changes started revealing why they were good decisions to begin with, I’m led to wonder if documenting intent is a good idea.

 

Is this what the intention behind commit messages is? The code documents the code, the comments document the pieces of the code that are non-obvious, and the commit messages document the intention behind each change?