Print a Month Project
Starting in July, I’m starting a new project to help sharpen my skills and maintain a consistent production. The basic principles are as follows:
- Every month I take a new picture
- That picture is then manipulated and prepared to the best of my ability
- The final result is a matted print
The goals are to fine tune my process, try new techniques, and increase my proficiency. The reason for dealing with a print is is for the work to reach its full potential.
Why every month, and not every week or every day? Mainly because I want to have an attainable goal. Something that is reasonable for me to do, yet will push me. Due to my schedule between work and church, I have far less time than I really want in the darkroom. I’m trying to make better use of my time in the darkroom. Additionally, the goal of one print a month allows me to really dig deep into a print and experiment with ways to make it better through dodging, burning, toning, or more creative approaches.
"Beyond" the Zone System
In the process of trying to coerce a working system in my darkroom, I purchased the book “Beyond the Zone System” because I know it has a lot to help understand sensitometry. What appeals to me is the ability to both test the speed of your film and the development time within 6 sheets. Since Ansel Adam’s film speed test takes seven sheets and an unknown amount of sheets for the dev test (at least one but in practice a few more), I’m all about conserving resources. The cost of the sheet of film is only one part of the cost—it’s the investment in time that I’m most concerned about.
BTZS starts out with a nice little overview of how paper and film work together to make the finished image. It also has a review of all the types of math and graphing theory that pertains to this testing process. The math’s not that hard, but the problem is in the way it’s presented. You can tell the author has a wealth of information, and he tries to make it accessible all in one or two chapters, but you almost end in confusion.
Where my head really starts swimming is when he gets in to calculating film speed. With Ansel Adams, it’s simply a density of 0.1 over film base+fog. The author covers the history and the pros and cons of how film speed was calculated over time, instead of just choosing one and teach how to do that one. It’s useful information, but the alternatives could be moved to an appendix to make that section more accessible.
With a proper handle of the basics of how the film and paper relate to each other, you can intelligently make decisions on exposure, development, and printing decisions. The road to understanding taken in the BTZS approach is very technical, which is not for the feint of heart. However, once you’ve learned the basics, you learn useful bits of information. For example, changing development times is similar to changing apertures—they both follow the same geometric progression of numbers (4, 5.6, 8, 11, 16…) to produce the same changes in final density. Shutter speed times and film speed numbers follow the same progression of numbers.
If you are serious about understanding more about how your materials work and respond to light, this book is definitely something you should have in your library. It will take time to “get it”, but once you do it will help you with your final results. You have a better understanding of why you choose a particular density for your print materials. You also have a better understanding of how zones don’t equal stops of exposure—yet the two still relate predictably.
Confronted with Concept Art
I’ve been going through Jeff Curto’s History of Photography podcast which has been very good and educational. Not surprising since this is Mr. Curto’s lectures from the class he teaches at the College of DuPage. I did get out of it what I wanted, which was exposure to history’s famous photographers. However, there is one thing I can’t wrap my head around; which is not Mr. Curto’s fault. It’s this whole thing with concept art. The music world has an equivalent called “performance art”. I don’t think it’s so much that I don’t get it, but more that I don’t want to get it.
To me, concept art or performance art is what happens when your left brain attempts to do the job that belongs to the right brain. In essence you as the viewer or artist are supposed to thrust your own intellectual ideas on the object of art rather than allow the art to speak for itself. In essence, it seems to me like the mental masturbations of someone pretending to be an artist telling the world that this boring or non-existent thing is art. For example, someone sits at a piano for 30 seconds in an outdoor setting, closes the piano and takes a bow. Someone erases another person’s painting and calls it art. It takes no skill to do these things. You are supposed to contemplate the ingenious mastery of perception or some other such nonsense.
Sure I come to art with a preconceived notion that art is supposed to be beautiful. I can get abstract art. Art is always introduced by folks like Michelangelo, DaVinci, etc. We then learn about impressionism such as the wonderful works of art by a Claude Monet. I can even get Picasso. So when I see photographic art in the same style I can wrap my head around it. I can understand it. I can see the beauty in the subject, even if I may not particularly enjoy the subject.
What I don’t get is how something that looks amateurish is supposed to be a modern interpretation of art. It almost seems to me as if the art community has become so inbred on its own philosophies and community that it has lost touch with the world. The people who buy these pieces of “art” don’t do it because they enjoy what it looks like, but rather because they look at it as an investment. I have to wonder if the concept art will truly be remembered a hundred years from now?
Do I consider myself an artist? Hardly. Sure I am pursuing photographic art, but I don’t count myself to arrived. In many ways, I want the art to challenge me and impress me. Not to challenge my understanding, but to challenge my skill and knowing what is possible with the medium. I’m forced to deal with left brain functions all day with my job, when I view art I want to exercise the other half of my brain. Concept art (and in the same vein performance art) fails to challenge me or impress me. My daughter created better work when she was nine.
Diving in to film testing and random thoughts
I’ve been having mixed results in the darkroom, so I’m in the process of at the very least improving my consistency. Part of that process is testing my film and development time for what I like to shoot. It hurts my feelings to use so much precious 4×5 film for the purpose—but I’ve learned something. My instinct to shoot at half the rated speed for my Fomapan (or Arista.EDU Ultra) film was right on the money. However, the development times for Rodinal 1:50 I got from Digital Truth are way off for the way I develop. When I tray develop, I am constantly agitating and rocking the tray back and forth. As a result I have way more contrast than I should.
How do I know? Well I do have an X-Rite 810 densitometer, which can be found on ebay for a reasonable cost. I don’t plan to use it all the time, but while I’m getting my process under control it’s becoming quite valuable. I found the minimum exposure that produced .1 over film base+fog which gave me an ISO of 100 for the Fomapan Creative 200 film. Great. Now, I’m trying to find the right development time that will give me a density between 1.25 and 1.35 for a Zone VIII exposure. The first time through I accidentally made the exposure for Zone VII (that’s zone 7 instead of 8), and used the recommended 10 minute development time for Rodinal 1:50. The density I got was about 1.89. So let me spell it out, it was way above what it should be. My second attempt corrected the exposure (more exposure, more density) and halved the development time to 5 minutes. The density I got was now 1.69, which is still way above what it needs to be. My two choices now are to dilute the developer or to use less agitation. If the time is below 5 minutes you will see some variance in results depending on how quickly you stop the development. I’m not done testing yet, and it is going much slower than I’d like because I don’t have but a few minutes at night to do one test.
Film testing is not a fun task, but in many ways I think it is necessary to go through to at least establish your custom times. The goal is to spend less time fighting my negatives to get a reasonable print and more time enjoying the results. The problem I’m running into is a lack of consistency in my negatives or detail in the highlight areas. The negative has it, but the paper can’t reproduce it readily. My scans came out nice but the prints were a lot more contrasty. Now I know why.
After I get my Arista/Foma film development process down, I may experiment with using my Silvergrain Tektol to develop the film. I’ll start with paper strength at 5 minutes and adjust density by adjusting my dilution or time.
Recreating Yesteryear Photographically
Many people have considered what makes a photograph look old. Of course, the best way to find out is to look at some old photographs yourself. The question becomes a bit muddier when you have to consider who took the pictures? Was it a professional, was it an average Joe? What kind of equipment did they have? Many old pictures are plagued by being just out of focus because the focus screens were just off. One obvious difference was the use of black and white film. They didn’t have color on one piece of film back then. In the 40s color was done by three frames of film each with a different color filter (red, green, blue). The composite became the color rendition. Color film didn’t make it onto one frame until the 50s. Even then, it was no where near as stable as the black and white film.
The archive of pictures I inherited from my grandpa was all shot on two types of film: Plus-X and Tri-X. The formulations have changed over the years, as has the backing (the original backing is not “safety” film, so it degrades over time). I’ve also noticed the exposure is all over the place. Mostly from using the “Sunny 16” rule. The sky was plain white, or there wasn’t a whole lot of shadow detail. The things that we take for granted now were not in existence then. Meters were either very expensive and only for the elite pros, or they just didn’t exist at all. These technical challenges aside, there is one thing that separates yesteryear pictures and pictures of today—and that is on the creative side of things.
Back in the day, a portrait was a formal thing. You dressed up for the occasion. Even the informal pictures had a certain class about them. I’m not necessarily romanticizing the past, but things have changed in the past 60 years. What is socially acceptable, and what is not. How people dress. The expressions on their faces. 60 years ago the world had finally ended its second war, a war that spanned both hemispheres of the globe. These people have a depth of character and presence in their eyes that you aren’t going to see in today’s average person. There are certain parts of the world today that have been ravaged by war for many years, and you’ll probably be able to see the same character in the eyes of people from those regions. But if you are in America, Western Europe, or even Japan most people have forgotten the horrors of war and what it does to a soul. Even if you had the equipment to make sure everything was in focus, and the exposure was nailed every time, you would still notice a difference between pictures of people 60 years ago and today. If you truly want something that looks retro, you have to put yourself in their shoes. Pay attention to all the details such as clothing, architecture, etc. Maybe you want to add mistakes to make it even more believable. It’s just something to think about.
The "Rules" of Photographic Creativity
Creativity is a very important aspect of photography, no doubt. From the particular exposure decisions we make to the timing and lighting, all of these require creative thought to get what you have in your mind’s eye. However, there are certain things that have been foisted on us that we hold to be “truths” or unbreakable rules of photography. Some people will tell you that there are no wrong answers—I don’t agree with that, but there are some questions that allow for a range of correct answers. For example, what should your exposure be in open shade at ISO 100? There is more than one answer to that question, and the answer is affected by whether you want some motion blur, or frozen motion, what photographic filters are you using, etc. But that is not the crux of where I’m going right now. There’s other things that are on the line.
“Thou Shalt Never Delete Any of Thine Pictures”
Says who? Think about this one a minute. Let’s say you do sport photography, and for every 1 good picture you have 40 that are either unusable or just average. If you shoot RAW, each picture consumes at least 10MB of space. Each game might consume upwards of 4GB of space. Are you going to keep all of these pictures indefinitely? Think about it, once the season is over and everything that is going to be done with these pictures has been done is there any reason to keep them? You can at least consider removing all the lackluster pictures. Storage is “cheap”, but it is exhaustible. Particularly in times of recession, you have to think about cutting loose the chaff. That’s not to say all work should be thrown out due to the fact there can be new uses for it. However, if you can’t think of a use for a picture now, and you aren’t particularly attached let it go.
You can learn from older pictures, but you should still be pressing forward and trying new things. The older pictures can be a source of inspiration, yet not every one of them will lend itself that way. Some people have been known to destroy negatives after a run has taken place, and I’ll be the first to tell you that there are some that I’m seriously considering destroying. Think about what would happen if you had a fire and lost everything. Your negatives (if you still shoot film), your hard drives, etc. and you had to start over. How many of you would really think about going back and re-shooting everything that was lost? I for one wouldn’t. I’d take it as an opportunity to re-invent myself based on the experiences I’ve had so far.
“Thou Shalt Use the Rule of Thirds, It is the Blessed Path”
The rule of thirds suggests that if you place your subject in the “power points”, your picture will be better. For example, if you dice your viewfinder with lines marking the thirds vertically and horizontally you will have a more “powerful” composition if you put something on those lines or where they intersect. This is a very useful compositional guideline, something we’ve taken from the great painters of yore. However, if you want your picture to be at rest, or static, that bulls-eye picture they tell you is wrong may just be thing the doctor ordered. Powerful is not always the emotion or reaction you want from your viewer. The rule of thirds is a very useful compositional tool, but there are other compositional tools you can use as well. Things such as repetition, diagonals, s-curves, color, contrast, etc.
If the rule of thirds is your only tool, you are a one trick pony and you are condemned to be “stuck”. Instead try to master how light and color affect the mood of your photograph. It’s amazing how a little fog, or some stray light highlighting your real subject improves the emotional impact of a picture. Use the light available, or possibly create your own light. Sometimes engineering the light in your picture is the only real way of getting what you want. If you can, walk around your subject 360 degrees. You might find a better viewpoint to improve the impact.
“Thou Shalt Not Allow Thineself to Enter Into a Slump”
It’s nearly impossible to think creatively all the time. We have times where we are “in the zone” and we intuitively think sideways. Then we have times where we either fall into a rut or are at a loss for the next big idea. The fallacy is that there are those that are creative and those that are not. The truth is that we all have creativity. The challenge is to look for inspiration. It’s OK to fall into a slump at times, because you have to think creatively to get out of it. If you are a one trick pony, learn a new trick and see where it leads you. If you have a variety of tools at your disposal, then it’s time to look in odd places for inspiration. Change your surroundings, give yourself a project. Give proper thought to the things that excite you and why they get you excited.
With all your doing, don’t forget to rest. Sometimes what you need to do is let go of a problem for a while and let the answer resurface all by itself. How many times have we been under crunch time, and you’ve been beating your brain all day, only to have the answer come to you when you are in the shower the next morning. When your mind doesn’t need to be actively engaged it’s OK to let it wander and see where it leads you. You can gain inspiration out of where your mind goes. Then you start thinking about how would you portray that in a picture. So it’s OK to let yourself enter a slump. That slump is usually the step before your next burst of creativity.
A Firm Foundation, or Shifting Sands
Yes, I’m a software engineer and a photographer, but first and foremost I am a Christian. I’ve been serving Jesus for over 20 years now, and I am saddened by the quality of people that call themselves Christian now. The word “Christian” means “of or like Christ”, and it was first used to describe the people in the church at Antioch. These people were Christlike, honoring the Lord with their lives. Part of the ills of people who call themselves Christian today stem from the societal ills we have in the world. Part lies on the shoulders of men who compromise the Word of God to fill in their auditoriums. They will answer to God for their compromise. The rest and majority lies in the hearts of those who only want to be hearers and not doers, having a form of Godliness but denying the power of God in there lives.
The bottom line is that God is real, Jesus is real, and he is intimately involved in our lives whether you recognize that fact or not. He wants to have a relationship with you, to empower you to live free from the shackles of sin. I know that atheists don’t want to acknowledge anything that does not fit for their finite minds to understand and quantify, but that doesn’t change the fact that God exists. It’s as if there are two people at the bottom of the well, one says everything is only blue and white outside the well and the other says that there are a wondrous variety of colors including green, red, yellow, etc. Just because one only can see blue and white (sky and clouds) does that mean that these other colors (grass, flowers, etc.) don’t exist? But I’m not talking to atheists right now. I’m talking to those that profess to be Christians.
Jesus gave us a parable about building a house on the rock vs. building a house on the sand. Jesus is that rock, and His Word is how he reveals himself to us. If we build our lives on anything but the Word of God we will fail, and great will be that failure. The problem with many churches is that they want to mix the Word and secular humanism. They want to add existential thought. They want to use psychology and situational ethics to define what is good and acceptable to the Lord. This is blasphemy. How can something that always shifts and changes be a foundation for a life that can withstand hard times? How can you expect your house to stand when your very foundation moves? The church of universities has done much harm to the minds and hearts of Christians in this regard, and it is by design. They site such ridiculous examples as “is it OK to lie if you are hiding refugees from the Nazis”. The premise being that if you weren’t a Christian you could lie and it would be OK because the Nazis are bad people. Of course that premise is faulty because if the Nazis were Christians there would be no need to hide refugees—they would not be bad people. Remember that my definition of Christian is “Christ-Like”, not someone who goes to church. All this is designed to wear down the hearts and resolution of Christians to do the Word.
The problem is that it worked. According to statistics the teenage pregnancy rate, divorce rate, age of losing virginity, etc. in the fundamental Christian churches are no different than the world. No different than those who don’t profess to be Christians. This is an outrage. Its because these kids aren’t taught how to contend with the world. These kids are merely babysat and patted on the head even though their lives are appalling. “Just name the name of Jesus….” Paul said that if Jesus is not raised from the dead than we are of all men most miserable. Why? Because a life in Christ means a life of death to self, a life of denying those lusts and passions that are normal to all men. Because we are not called to a natural life, but a supernatural one where Jesus empowers us to live free from the power of sin (Rom. 6:14).
There has to be a relationship with Jesus to be successful. In John 15, Jesus is giving his parting words to his disciples. He admonishes them to abide in the vine, and that He is that vine. That vine that brings life and power to the branches to be able to bear fruit. The fruit of a Christian is a changed life. It’s the ability to remain pure in an impure world. It’s the ability to know that Jesus is real when everyone tells you He isn’t. Its a life that is an example of Jesus to an unbelieving world. How can you name the name of Jesus and not have any fruit to back it up? How can you claim to be alive when the fruit of your life is death? How can you say you are like Jesus when you look and smell like the world?
In Revelation 3, Jesus admonishes the church at Laodicea that he wishes that they were hot or cold, but because they are luke-warm He will vomit them out of his mouth. It’s not time to play games. It’s not time to mix the fire of God’s Word with the cold of this world’s system. As Isaiah challenged Isreal, choose this day who you will serve. Quit riding the fence. If you are going to be a Christian, be like Christ and He will give you the power to do it. If you are going to be worldly, than quit pretending to be a Christian. Stop lying to yourselves. There is nothing more sad than someone who claims to believe something but everyone around them can tell it isn’t so.
Sure this is a strong word, but its been on my heart lately. If it’s wrong prove it in the Scriptures, but I can’t see anywhere that allows you to claim to be like Christ and live like the devil. People who do that are liars, and there is no truth nor life in them.
What I Learned at my Second Photo Competition
My first photo competition went really well, and I even took home second place for intermediate black and white. The theme was abstract photography. I noticed something with the advanced tier of photos, and that was many were displayed at 11×14. I thought I’d take a gamble and do some 11×14 pictures to show off the detail in some of my pictures. The gamble backfired.
Photo competitions are very subjective, so the judge picks the pictures that fit his/her bias and preferences. I take it as a learning experience. This particular judge cared almost more about the matting and presentation than she did about the content of the picture. She absolutely did not like pictures at the largest size allowed for the competition. She pretty much disqualified anything that did not have a top mat—which would have been impossible with the 11×14 pictures. The maximum size for the whole mat/picture combination is 11×14. That meant three of my four pictures did not get a second look. While I was following the competition rules, they just did not make the cut because of the presentation.
It sounds like I’m ranting, and maybe I am a little bit, but there is a point coming. I took a closer look at some of the advanced offerings and noticed that the ones that were 11×14 were both mounted on foam board (careful with the cutting, ragged edges got disqualified) and they had a border. The black border helped frame the picture in the absence of a top mat. Huh. I didn’t have the time to do the same, and I can’t seem to cut foam board without snagging the edges. Even I know that looks crappy.
Bottom line is this: photographs need to be properly matted to help enjoy them better. A white mat is most common, but we’re allowed to use black and gray mats as well. The choice of mat colors was intended to give a certain amount of flexibility without really tipping the scales in favor of those with better packaging skills. That mat provides a boundary, if you will. The boundary hides the edges of the photograph.
So, what happened with the final photograph I entered? Apparently the judge felt it should be tack sharp—which is not the look I wanted for that picture. So the bottom line is that we disagree on that point. I understood where she was coming from, her background is wedding photography. Her clients want tack sharp pictures. That is her bias. The pictures she chose were in most cases commercial. Not many she chose had emotional appeal. That’s why photo competitions are so subjective. Had she been in a different mood, she may have picked the one she turned down.
Bottom line is this, no matter how altruistic a competition may claim to be, present yourself well. Mat your work as best you can. Hinge the top mat to the back mat. Secure the picture to the back mat. It’s never really just about the pictures.
Untangling a Mess
Sometimes through the best of intentions meeting customer expectations and getting critical functionality out the door we create a mess. So what happens if the organic growth of complexity reaches the critical point? Obviously it needs to be addressed, or this rats nest of code will seriously impact your ability to maintain the project, or worse it impacts the performance and stability of the application.
There are all kinds of rats nests that lay in wait ready to spring into your code. These range from overly complex processing to a series of database updates and reads that should be packaged up and optimized better. These complexities come from performance optimizations, or from needing to track more meta-information about your project’s data. Sometimes the complexities start out with a poor design, but most of the time it comes from a decent design that just wasn’t cleaned up.
Analyzing the Problem
The first thing to do when analyzing a rats nest is to document the before and after states. What should the data look like when we perform a certain action? Any solution that breaks this contract will cause problems in the application. Once we’ve documented what the application is doing that we don’t expect, the first thing to do is to remove those changes from the system. Since we are in the documentation and analysis stage, we just have to cross out those actions from the change package.
The next step is to figure out how to cleanly make sure that the end result is what we expect, and that there is no surprising work done. Having simple, well defined packages of change will help you get a grasp of the next steps you need to take. It can also provide its own performance improvements as the system isn’t doing unnecessary work.
The final step of analysis is to figure out how drastic the change has to be. Can you get away with a few key changes? Do you really need to rewrite whole sections of code? In essence, this is where we assess the risk of the proposed changes. Are there ways to mitigate the risks and go through with it? Can we perform the work in stages spread out over more than one release? How long is it going to be to make these changes? How long would it be to pursue an alternate solution.
Solving the Problem
There are several ways to manage the structure of your code, and one size definitely does not fit all. Something like Design Patterns by the Gang of Four (Gamma, Helm, Johnson, Vlissedes) provides several common object oriented solutions to common programming problems. Too many people have used this book as the “Holy Grail” of software development and have erected crystal cathedrals of software in homage to the GoF. It’s a tool to help you think of ways of solving a particular problem. It’s not the doctrine of all software design. Nevertheless, don’t throw the baby out with the bath water. You can use solutions listed in that book, but implement them differently than they suggest.
Perhaps the right solution would be the “command pattern” which lets you create an object that performs the logic for a change. Assuming you have a fairly low number of changes, this can be a very clever solution. However, if the number of command objects suddenly explode into a large number it can introduce its own management problems. The command pattern can be an attractive way to deal with a finite set of complicated database transactions.
Maybe you need a proper Finite State Machine (FSM) and use the “state pattern”. With each state having a well defined start and end point, you can easily test the individual states in isolation. Just don’t forget to test the whole set together.
No matter how you choose to solve the problem, you have to ensure that you have adequate testing. Make sure that the changes you need are the only things being changed. For example, nothing else should be touched with your information than what you intended to touch. Being creative, you can build a testing infrastructure that extends your unit test tool to check whether values have changed that should remain the same. In fact unit testing is even more critical with cleanup work.
Intro to Functions
When you are just writing quick scripts, you can use Ruby all you want and be happy. However, there comes a point where you have to do the same thing in a bunch of places. Functions are a way to organize the logic in your code so that you can re-use it in more than one place. I’ll introduce how to do math at the beginning, but functions aren’t only for numbers as we will show later.
Doing Some Math
As long as you are working with numbers, you will have to remember some symbols. In your math text books you will see symbols that just don’t exist on keyboards and requires different key combination to make them show up. The good news is that the conventions for replacing mathematical symbols in code is pretty standard across languages. You only have to learn them once, which helps.
- + addition
- - subtraction
- * multiplication
- / division
- % modulus
- ^ exponent
- () group expressions
Math expressions are performed in algebraic order. In short, that means that expressions are evaluated in the reverse order from what I listed. Parentheses first, exponents next, then multiplication, division and modulus, finally addition and subtraction. Just to make it clear, look at the following code:
puts 4 + 5 * 6 # 34 puts (4 + 5) * 6 # 54 puts 4 + (5 * 6) # 34
It’s a good habit to use parentheses to make things clearer. There’s a few more symbols that allow you to do bit manipulation, but then I have to explain the math behind it. Let’s focus on this level of math for now. Let’s say we want to do a little trigonometry and calculate the area of a circle. The mathematical formula for the area of a circle is πr2. So how do we get a hold of the value of π? There is a Ruby module called Math that has the value of π and other more advanced functions.
Ok, so how does the expression look like in Ruby?
radius = 5 puts Math::PI * (radius ^ 2) # 15.707963267949
I added the parentheses to make it clearer that the exponent (raising to the power of two) comes first. So what if we wanted to reuse this function anywhere? We would have to create a function to do it. It’s pretty easy, and you will use the same construct in another post when we talk about creating our own methods. Let’s create our function:
def area radius
Math::PI * (radius ^ 2)
end
So what’s going on here? The word def is a Ruby keyword that tells Ruby that you are creating a function. After that, is the name of the function. Finally we have the list of parameters. A parameter is a name we give to a value that you pass to the function. Basically, the function is going to do something with that value—even though it doesn’t know what the value is first. The next line bears some explaining.
Functions can return a value, which is usually their whole point. However, we don’t see any words that say “return this”. It’s probably the most unintuitive thing you’ll run into with Ruby, but the last expression in a function is the value that’s returned. It’s a carryover from Smalltalk, and once you understand that it becomes a little more understandable. If we had one more line that just had the number 2 on it, then the function would always return the number 2—which is wrong for what we want. What some people do to make things a bit clearer is to use the keyword return . That keyword is designed for letting you leave a method early for some cases, but it works just as well. It’s probably not a bad habit as other languages require you to use it. The method would now look like this:
def area radius
return Math::PI * (radius ^ 2)
end
The keyword end is something we saw already when we were doing loops in the last lesson. This keyword is used to end any block, so you will use it a lot.
Not All Functions Are for Math
I introduced functions with math because that’s where the idea came from. But most problems don’t require the use of heavy math. Ruby isn’t designed to be a math engine anyway. Just for fun, let’s create a function that will turn a number into words—Japanese words to be exact. It’s only fitting as Ruby came from Japan after all. Just to save us some work, we’ll limit ourselves to the range from 0 to 99. To do that we need to use an if statement. The if statement let’s us do something if it is true, but skips the code inside if it is not true. We also want to raise an issue so that the calling code knows that they asked something we can’t deliver. The keyword is raise , which is rather convenient. You can “raise” any object, but we will just use a string. The code looks like this:
if not (0..99).include? number
raise "We can only translate numbers between 0 and 99"
end
I’ll include the solution below, and just expound on things in comments. Your job is to expand the method to do up to 999, or to change it to another language. I’m using Japanese partly because it’s easy to do with code. Other languages have more exceptions.
def to_japanese(number)
#
# Protect our method from trying to work on numbers
# it doesn't support
#
if not (0..99).include? number
raise "We can only translate numbers between 0 and 99"
end
#
# Keep it simple, use the variations of four and
# nine that work in the tens column as well as
# the ones column. These are the numbers from
# zero to nine.
#
numbers = ['rei', 'ichi', 'ni', 'san', 'yon', 'go',
'roku', 'nana', 'hachi', 'kyu']
#
# Modulus gives the remainder.
# 12 divided by 10 is 1 with a remainder of 2.
# It's a good way to get just the ones column.
# Then we use regular division to get just the tens column
#
ones = number % 10
tens = number / 10
case tens
# When we are doing 10 - 19
when 1
japanese = (0 == ones) ? 'ju' : 'ju ' + numbers[ones]
# When we are doing 20 - 99
when 2..9
japanese = numbers[tens] + ' ju'
if (ones > 0)
japanese = [japanese, numbers[ones]].join(' ')
end
# Otherwise we are doing 0-9
else
japanese = numbers[ones]
end
return japanese
end
So there are a couple things I need to explain above. First is the case, when, else construct. The case statement tells Ruby that we are going to use the following expression (in this example the expression is a variable) with a bunch of comparisons. It’s a little nicer than doing a bunch of if/else statements. The first match is what gets run. Each case that we are checking is marked with the when statement. To translate it to English, it’s like saying “when tens is 1 do this”, “when tens is in the range 2..9 do that”, “otherwise do this”.
The next thing I have to explain is the (something) ? true : false construct. It’s a shorthand for an if/else statement. Essentially, we are saying that if the ones column is 0, just return ‘ju’ otherwise return ‘ju ’ plus the translation of the ones column. Have fun!
