D’oh! My numlock issue was . . .

Posted by john in Technology

D’oh!

Because of the placement of the ThinkPad NumLk key, it seems as though you would have to press the function (Fn) key. So I did that. Didn’t work. Then I tried it in conjunction with many other keys: Ctrl, Shift, Alt, etc., etc. A student came up and did the same things. Couldn’t budge it.

After perusing the deeply buried documentation on the Status lights, to turn off NumLk you simply type: SHIFT NumLk. No Fn.

Obvious. But I have seen other wrestle with this in exactly the same way I did!

Thanks for bearing with me . . .

Ruby Debugger

Posted by amy in Ruby on Rails, Ruby

Someone in my section asked about debuggers for ruby code, and I said something unhelpful like “What’s wrong with puts?!” but promised to get back to them with something more useful. So if you want to, go read about Ruby-Debug here.

Today is Blog Action Day

Posted by john in Ruby

As you may know, today is Blog Action Day, and one is supposed to write a post about the environment.

So I’m going to do my part.

If you have an environment variable in your operating system, such asĀ  “Path” you can get access to it in Ruby with ENV[’varname’]. So, in this case, you’d ask for ENV[’Path’]. (On Linux and Mac OS and even some Windows machines, it would be ENV[’PATH’].)

It doesn’t seem like a very worthy topic for Blog Action Day, but there it is. Enjoy!

Musing about Mixins

Posted by amy in Ruby

Here’s a blog post that does a nice explanation of the difference between ruby module mixins and Java interfaces:

Interfaces in Java and .NET are exactly like legal contracts (where the compiler is the all-powerful judge). If you implement an interface yet don’t meet the terms of the contract, the judge refuses to allow you to proceed.

Mixins in Ruby are more like promises than contracts. When you agree to pick up a friend at the airport, you don’t sign a contract, you promise you’ll be there. The punishment is purely social: if you break a promise, your friends won’t do stuff for you. Here’s an example.

The blog entry then gives an example using Comparable, so if you’re having trouble grokking mixins, go read the rest.

Instances of the class Class

Posted by john in Ruby

Awhile ago, a student wrote me with a question about an instance variable used right after the class declaration, i.e., inside of a method. Here’s how I summed up this puzzler in code to the group:

class Example  # The following line is the issue. It looks like a instance variable has been set to
  # a value, but it isn't visible later on.
  @var1 = [ 1, 2 ]
  p "Just inside 'class Example' but outside method, @var1 = #{@var1.inspect}"
#  p "Just inside 'class Example' but outside method, self = #{self}"

def initialize
    p "Inside ' Example.initialize', @var1 = #{@var1.inspect}"
#    p "Inside 'Example.initialize', self = #{self}"
@var2 = [ 3, 4 ]
end

def dump
    p "Inside ' Example.dump', @var1 = #{@var1.inspect}"
    p "Inside 'Example.dump', @var2 = #{@var2.inspect}"
#    p "Inside 'Example.dump', self = #{self}"
  end

end

Example.new.dump

class Example
  p "Re-opened class Example, outside method, @var1 = #{@var1.inspect}"
#  p "Re-opened class Example, outside method, self = #{self}"
end

If you remove the comments for the statements showing the value of self in various places, you will find that the value of self just inside of the declaration of the class is the name of the class, i.e., Example. Therefore, it would seem, @var1 is an instance of Example. What does this mean?

Ruby is more fully object-oriented that most other languages: Its model is much closer to, say, SmallTalk than it is to Java.

In Ruby, when we declare a class, we are creating a constant (note that capital letter for “Example”) that is a reference to a single object that is an instance of the class… Class. And how can we begrudge this instance its own instance variables? The syntax is a bit confusing, because we are used to variables prefixed by @ to be instance variables of instances of that very class we’re declaring (i.e., instances of Example). But those instance variables are referenced inside methods.

Hal Fulton says: “Variables starting with a single @, defined inside a class, are generally instance variables. However, if they are defined outside any method, they are really class instance variables.” He goes on to say: “Class instance variables cannot be referenced from within instance methods and, in general, are not very useful” (The Ruby Way, pp. 56-57).

Now, let us return to something we talked about briefly in lecture. Remember “extend”? That was weird, wasn’t it? We were able to bring in stuff from a module to a specific instance. Well where the heck does that stuff live? Well, in the module. But it suggests that maybe we could add methods to a specific object, not just to a class. Ruby facilitates this.

Again, Fulton (pp. 61-62):

A singleton class in Ruby is the classlike entity where methods are stored that are per-object rather than per-class. It is arguably not a “true class” because it cannot be instantiated. The following is an example of opening up the singleton class for a string object [listen to what Fulton is saying: Opening up a specific object, not the class] and adding a method:

str = "hello"
class << str      # Alternatively:
  def hyphenated  # def str.hyphenated
    self.split('').join('-')
  end
end

p str.hyphenated

…Because the method hyphenate exists in no other object or class, it is a singleton method on that object…

But remember that in Ruby, a class is itself an object. Thus we can add a method to the singleton class of a class, and that method will be unique to that object, which happens to be a class. Here is an example:

class MyClass
  class << self   # Alternatively: def self.hello
    def hello     # or: def MyClass.hello
      puts "Hello from #{self}!"
    end
  end

end
MyClass.hello

But you will notice that this is simply what we call a class method in Ruby. In other words, a class method is a singleton method on a class. We could also say it’s a singleton method on an object that happens to be a class.

Whew. Let us return now to Fulton’s claim that class instance variables are not very useful. I think they are sometimes. Suppose you wanted to track object creation. You might write something like this:

class Example1
  @@number_of_instances = 0
  def initialize
    @@number_of_instances += 1
    print "There have been #{@@number_of_instances} instances of Example1 created.n"
  end
  def num_instances
    @@number_of_instances
  end
end

e1a = Example1.new
e1b = Example1.new

Clear enough. But is it right that the instance can see the number of instances of the class? Shouldn’t we be able to keep that number private to the class? Yes we can. We can keep the number of instances in a class instance variable:

class Example2

  @number_of_instances = 0

  class << self
    def bump
      @number_of_instances += 1
      print "There have been #{@number_of_instances} instances of Example2 created.n"
    end
  end

  def initialize
    Example2.bump
  end

end

e2a = Example2.new
e2b = Example2.new

Notice here I do have to call the class method bump to get my counter incremented. But at least now the total number of instances is private to the class instance. Is there a way to get rid of the need to call Example2.bump? Yes there is, but you would have to override Class.new. I will leave that as an exercise for the reader. :-)

Ruby-ize this

Posted by amy in Ruby 3 Comments »

If you’re interested in making your code more ruby-esque, ruby fleebie has an ongoing feature called Ruby-ize this.

Strategies for working on assignments

Posted by john in Assignments 3 Comments »

Gather ’round, I’d like to share some strategies for working on the assignments. I could have talked about some of this earlier, but I think now is really the key time, when some of you are 10%, 30%, or 70% done, but not sure how you’re going to get to the finish line.

  • The first thing I want to stress is to get some code working first. While the perfect submission for #2 will be a true Ruby one-liner with few or ideally no extra variables, statements, destruction of input data, etc., if you see a solution that has lots of lines, extra variables, go for it: then start refining. “Every block of stone has a statue inside it and it is the task of the sculptor to discover it.” — Michelangelo
  • Remember, you’re learning. It’s hard. You are literally building new neural pathways in your brain. Please, drink lots of fluids.
  • Yes, I did say that some people would finish in 4 hours. It’s a bell curve. When I took my first serious Java course back in the 1930s, I remember vividly working on it 20+ hours a week, and my code never really completely worked. But fortunately there was partial credit in that class, just like this one. And I learned a lot. I became an expert at making mistakes, and even today I say to Java developers: “Oh, yeah, I did that once.” Amy tells me that while she’s written a lot of Rails code, the concept of the one-liner was a challenge . . . “and look at me now, injecting all over the place!”
  • Be a bit self-conscious about your work strategy: If you think you’re more comfortable reading and then doing, try it. But don’t be afraid to reflect on your assumptions and switch things around if you’re not making progress: try alternating reading with doing.
  • Remember that the Pickaxe teaches in four different ways: Discursively, about Ruby in general (chapter 2); in an expository fashion for Ruby concepts (chapters 3-9); definitionally, in the chapter on the Ruby Language (chapter 22); and finally, encyclopedically — the API docs for built-in classes and modules (Chapter 27). These different modes tap different ways of understanding. (Someday there will be a Head First book on Ruby and Rails, which will truly try to educate all parts of your brain.)
  • One student who shall remain nameless turned in her assignment a few days ago and also shared her strategy for finishing. She went over the lectures, and made a list of capabilities that I presented. Then she went through the assignment, and made a list of “requirements” for each item. Then she matched them up. I think she did this informally, in her head — it was her way of putting her work into a productive order. In many cases, she used the lecture as a way to focus on sections of the Pickaxe. And, of course, she tried everything in irb.
  • Rubber ducking (http://compsci.ca/blog/rubber-ducks-help-best-with-computer-science/) can be very helpful. I happen to have plastic rubber ducks on my monitors, both at home and at work, and I discuss my code with them all the time.

    picture-7.jpg

  • Tossing code and starting over. The idea is that you probably are there conceptually, but your current implementation is messing you up. The classic popular culture example of this is a scene in the movie “A River Runs Through It,” when a boy is essentially being home-schooled by his dad. He writes an essay. The father reads it and strikes words, finally telling the boy that it is better, but that he should tear it up and do it again. What is happening is that the boy is internalizing some ideas about elegance and concision in writing. “Programming is a kind of writing.” — Gerald M. Weinberg
  • Do ask questions! If it seems useful for others, Amy or I will post the question and the answer back to the e-mail or to the course site, without attributing the question to you.

Good luck!

My Ruby and Rails RSS feeds

Posted by john in Ruby on Rails, Ruby

So my last posting on feeds was everything but my Ruby/Rails RSS feeds and engineering feeds.

Here are my biggies.

General engineering / software / project management

  • Rands in Repose (Already mentioned)
  • Joel on Software - (Also on Amy’s list.) This was one of the first blogs to sum up a body of common knowledge regarding software, project manager, and software business practices. No one thing Joel Spolsky said was particularly astounding, but the general strand of good sense was highly valuable. Among other things, Spolsky has well-defended the idea that great developers need great offices, great tools, decent pay, and the right amount of work. Not much new stuff from Joel recently.
  • That’s really it.
  • There are some other bloggers that I’ve been avid for in the past, such as Jeremy Zawodny, Matt Raible, Phil Windley, James Gosling, Cameron Purdy, Eric Sink, and others, but it’s amazing how a lot of these folks have cooled off. Also, sometimes bloggers become quasi-famous, and then they think they can blog about whatever they want. But guess what, I was interested in their core competency. So they get unsubscribed.

Ruby and Rails

  • Amy and I both subscribe to Err the Blog, Rails Envy, Jamis Buck, Amy Hoy, Nuby on Rails, Riding Rails, and Loud Thinking. See Amy’s post to get those URLs.
  • Headius, Charles Nutter’s blog on JRuby.
  • Ruby Inside, the blog of Peter Cooper, author of Beginning Ruby.
  • Ola Bini’s blog; Ola is a developer at ThoughtWorks who contributes to JRuby. Ola seems to be one of the smartest bloggers out there. I learn something from every post.
  • O’Reilly Ruby. The best posts are by Greg Brown, who has talked to the Boston Ruby Group.
  • Rubylution - This one has a nice post on operator precedence that builds on what I warned you about regarding and, &&, &.

That’s enough for now. Let the group know if you find any interesting blogs that are relevant to the course.

Beginning Ruby - half price

Posted by john in Ruby

If you’ve looked at the books page, you know that I like Peter Cooper’s Beginning Ruby.

Cooper reports that it can now be acquired for 1/2 the price.

Lecture 3 and Assignment 3

Posted by john in Uncategorized 3 Comments »

Folks,

A few notes:

1. I’ve posted the slides and a link to the slide outline:

http://e168f07.7fff.com/private/lectures/

I *will* be tweaking Lecture 3, so stay tuned for a revised version that fixed the “spaceship” example and a few other things. There is also a ZIP of some scripts for Lecture 3 that are easiest run outside of the browser (i.e., the normal way: See below).

2. There is also a link to download all of the lectures in one bundle. This includes the code to make the dynamic Ruby in the slides work, so it’s a hefty download.

3. The provisional version of Assignment 3 is here:

http://e168f07.7fff.com/private/assignments/

To read the instructions, open instructions/rdoc/index.html

The requirements for the assignment will not change. A later release of the assignment will include expanded tests, and possibly more documentation on some of the methods. If you’re an early bird who plans to look at this right away, by all means e-mail me requests for clarifications and I try to get them into the next release.

4. I will make a screencast that shows how you would work on Assignment 3, running the tests as you study the assignment.

5. I left out something rather important in last night’s lecture:

We have now moved from working in irb to writing full-fledged Ruby scripts.

A multiple-line Ruby program goes into an ordinary text file. It should have the file type .rb. Examples:

game.rb
card.rb

etc.

To run the script, you type:

ruby game.rb

See Pickaxe, p. 7.

Linux and OS X users: Of course, you can make the name of the file just ‘game’ and use sh-bang notation to define what should run the file (see p. 7, note 2) and chmod +x the file. And, of course, you can stow your scripts anyplace you want and put that location in your PATH.

Windows users: The one-click installer does some magic so that if you have a script in your current directory called, say, game.rb, and just type ‘game’ . . . and it runs. Or is supposed to. If you installed in other ways, this might not work, and it’s a bit of a pain to get set up. If you’re interested, I will circulate instructions.

WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login