Getting to Done
Tonight’s presentation on higher order procedures is now listed on the Presentations page to your right. I’ll be adding some practice exercises later, but feel free to check out what I have already.
Tonight’s presentation on higher order procedures is now listed on the Presentations page to your right. I’ll be adding some practice exercises later, but feel free to check out what I have already.
Look ma, I made my own object! It doesn’t handle state that well, but at least it can be passed messages and told to do things.
def make_number(x)
lambda do |op, *y|
if op == '+'
make_number(x + y[0])
elsif op == '-'
make_number(x - y[0])
elsif op == 'val'
x
end
end
end
my_num = make_number(5) => <#Proc>
my_num.call('+', 7).call('val') => 12
In case you can’t tell, this object creation makes use of higher order procedures. The make number procedure returns the anonymous procedure created by lambda. This form of object creation is not terribly practical, but it sure is cool.
Time to play with synonyms. Let me know which versions you like better.
result = 0 0.upto(arr.length) do |i| result += arr[i] end
or
arr.inject{|x,y| x + y}
How about this one?
0.upto(arr.length) do |i| arr[i] = 10+arr[i] end
or
arr.map! {|x| 10 + x}
Higher-order procedures are h0t!
So, I’ve finally started doing actual research for this presentation beyond asking, “What do I already know?” First stop on the research train? Blocks and Closures in Ruby over at Artima. It’s an interview with Matz (the creator of Ruby for those of you not in the know) discussing how cool it is that Ruby supports blocks and closures. Read on to get an abrievated version of what goes on in the article.
Remember how I said that we would be seeing a lot more about higher-order procedures on this site? Well, I’m giving a talk on using them in Ruby this coming Tuesday. All of my research will be posted here along with the final presentation. So get ready to read, because there’s going to be a lot of information coming at you.
Higher order procedures are something that I will talk about a lot here, so let’s get straight what they are. Higher order procedures are procedures that take a procedure as an argument or have a procedure as the return value. That being said, read more to see them in action.
Do you have code that looks like this?
if ((var == 'foo) or (var == 'bar') or (var == 'other') or (var == 'stuff')) do things end
If your answer is yes, then try this little trick to make your code more legible:
if ['foo', 'bar', 'other', 'stuff'].include?(var) do things end
As an added bonus, you can use ‘%w’ to make the array creation cleaner:
%w|foo bar other stuff|
I love how Ruby makes my code squeeky clean.