Aschenblog: Thoughts on Code and Fabrication

Protected and Private Visibility Modifiers and Inheritance in Ruby

During a recent code review at work, I was surprised by how Ruby handles private and protected method visibility modifiers in derived classes. The behavior is distinct from visibility modifiers in other languages like Java. Specifically, you can call a private parent class method as is demonstrated by the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
class A
  private

  def foo
    puts "foobar"
  end
end

class B < A
  def bar
    foo
  end
end

I did some experimentation in the irb console. As expected, one may not call the private method foo on an instance of A:

1
2
3
4
> A.new.foo
NoMethodError: private method `foo' called for #<A:0x00000102a0b498>
  from (irb):7
  from /Users/sela/.rvm/rubies/ruby-2.1.1/bin/irb:11:in `<main>'

What surprised me is that in the child class B that we can call foo on the parent class. Again, back to irb:

1
2
3
> B.new.bar
foobar
 => nil

Fast Autocompletion With Tries

Tries (pronounced ‘try’ or ‘trie’ as in retrieval) is an ordered data structure often used to store strings. It is a type of tree where the decoration on each node represents the position of the element being stored. If we store a string, then a depth first search of the tree to a leaf node will visit characters that make up that string.

Tries are great for super-fast autocomplete search. A breadth first search from any given point in the tree will find an exact match (if it exists), then matches one character away, then two and so on down the tree.

To build a trie we will need a recursively defined node called TrieNode. Let’s take a look at some Ruby code that we will use to build a Trie:

Popularity Trends in Programming Languages

Full disclosure: I am a Ruby and Java developer.

Everyone has their favorite pet languages (myself included) and I realize that this is a topic that evokes some feelings among my peers. In recent years, I strove to be more agnostic about tools and languages. While I try to be careful about making predictions, the languages and tools that are relevant now may fall out of favor in the industry in a few years. I’ll try stick to what I discovered, but I realize that my perception is colored by my experience.

I reviewed several indexes and articles including TIOBE, Transparent Language Popularity Index, IEEE Spectrum: Top Programming Languages, PopularitY of Programming Language Index, RedMonk Programming Language Rankings, Programming Language Popularity Chart and GitHub Language Trends and Fragmenting Landscape

While there was correlation between highly ranked languages between the indexes, none of them were the same. Several metrics were used including number of open source projects, number of lines of code, number of tracked bugs / issues, number of tutorials and numbers of search engine searches. The list goes on and on. How these metrics were weighted had a big impact on the overall ranking results.

In alphabetical order some of the most highly ranked languages are C, C#, C++, Java, JavaScript, Objective-C, PHP, Perl, Python, Ruby and Visual Basic. About half the indexes I reviewed had C and Java in the top two spots.

Ruby Quiz

I listen to the Ruby Rogues Podcasts on my way to work in the morning. A number of episodes focus on learning, education and keeping your skills sharp. I learn best by working on small projects to enhance my understanding of different aspects of a programming language. I was looking for some non-trivial example problems to work on and found the Ruby Quiz.

At the time of this blog post, the website has over Ruby 150 programming problems with several candidate solutions. The best of these were compiled by Ruby Rogue James Edward Gray II (Twitter, Github, Blog). While the book is out of print, I found a digital copy available on IT Books.

Happy hacking!

Something to Show at the End of the Day

Sometimes it is difficult as a software engineer to feel connected to our work product. At the end of the day, what can be demonstrated and communicated to others? It is a little easier when developing user interfaces as at least we have something we can show visually. A more cynical view is that all we did today is change some bits in a computer. This is why I like working with wood. I come up with an idea and am rewarded by seeing its physical instantiation.

I find that projects that engage both the analytical and creative parts of my brain are especially fun. Last summer I started making some custom wooden parts based on Voronoi Diagrams (at left).

First, a number of seed points are generated. Then the space is divided into Voronoi regions, which are sets of points closest to a seed point than any other. Typically, each region has a randomly generated color. The black dots in the image indicate the location of the seed points.

First, we will create a small helper class that will encapsulate a point’s position and help us calculate the distance to a given pixel.

Text Messaging Made Easy With Twilio

A few months ago I was determined to find out how to send and receive SMS text messages programmatically. After some research, I found that Twilio has a range of communication tools for developers for SMS / MMS, voice, mobile and web. They take care of low level details which facilitates the process of focusing on the core app. Their documentation is excellent and you can experiment with their tools for free.

When using a trial account, you can set up a phone number for free in just a few minutes. To get a number, click on the ‘NUMBERS’ tab and then click the link ‘Get it now’, which should show a page like the following:

Click the ‘Get started’ button. Note that you will have to enter in a number (e.g. your cell phone number) that you want to communicate with for the trial account to work. A short verification process is required. However, this limitation is removed if you upgrade to a paid account. Try out the test drive page that allows you to send a SMS message to yourself to ensure it is working.

Generating Code From Images of Color Gradients

I needed to incorporate smooth color transitions into a few projects I worked on several months ago. I wrote a 3D virtual terrain generator and wanted to color areas based on altitude. Higher elevations should be colored white (mountains), medium elevations should be colored green (grass) and lower elevations should be colored blue (water). A second application for these transitions was a series of particle systems (see video below). Changing particle color as a function of age allows effects like fading to black before a particle is removed. We will come back to particle systems later with a small demo at the end of this post.

To achieve color transitions in my programs, I figured that raster images with color gradients could be used. Programs like Adobe Photoshop or GIMP are excellent tools to use for this purpose. As an aside, I also enjoy using the ColorZilla Ultimate CSS Gradient Editor for web projects. The problem I faced was getting red, blue and green values at each pixel along the gradient into code.

Maps, Lasers and Bamboo

I spent a week over the winter at 8,500 feet in the mountains at Old Sky Valley Ranch near Tabernash, Colorado. It is an inspiring place and I undertook a project with fellow GIS developer Nicholas Hallahan (https://github.com/hallahan/ http://www.spatialdev.com/#about) to craft a gift for one of the ranch families.

The project involved quite a bit of GIS modeling and graphic design work. The spatial data was obtained from a variety of sources including the USGS National Map Viewer (http://viewer.nationalmap.gov/viewer/) where we found the contour data. We also obtained some of the road, hydrology, and cadastral (building footprints) data from the Grand County, CO GIS Department (http://co.grand.co.us/170/Digital-Data-Sets). Much of the fine grained details of this data were missing, such as some of the less develped roads and the precision of bends of the rivers and streams. This was achieved by hand digitizing from satellite imagery features that were missing in OpenStreetMap and then importing that final product. This part was a lot of fun, and in turn we got a new feeling and perspective of the geography of the area.

2D Fractal Terrain Generation

A while ago I discovered a simple algorithm to generate infinite fractal terrain. One application for this is to produce mountain-like backgrounds for 2D side-scrolling video games.

This is called the midpoint displacement algorithm. It works by recursively breaking a line into smaller and smaller segments and at each step changing the Y-value up or down by a random amount. The amount of change is reduced by some amount at each step to produce a rough or smooth looking mountain scape.

The blue lines (pictured right) indicate the location and amount of displacement from the previous iteration.

Here is an outline of the algorithm:

  1. Find the midpoint for the line segment
  2. Assign the midpoint to the average of the endpoints (L + R) / 2
  3. Generate a random number between -1 to 1 and multiply by the displacement value. Add this to the midpoint value.
  4. Recursively subdivide this line and reduce the displacement value by a fixed amount (a roughness parameter)
  5. Repeat previous until fractal is sufficiently detailed