Bitcoin maximalist.

Thoughts & Technical Writings.

How to: Use binding.pry More Effectively Within Enumerables

| Comments

what is pry?

When I first discovered the Pry gem, I felt like I’d won the lottery. At long last I had found a gem library that enabled me to simply insert a line of code - binding.pry - anywhere into my codebase that would drop me into an IRB session at that exact point at runtime. It sort of feels like air dropping a team of Ruby SEALs into enemy lines in order to eliminate those dreaded bugs.

using pry: best practice

Let’s talk about a quick example of using Pry in a Ruby file.

Let’s say you have an array of 106 elements, and you’d like to iterate through each one and call a fancy method on it:

BAD USAGE OF PRY:

1
2
3
4
5
6
(1..10**6).each do |i|
  collatz = Collatz.new(i)
  collatz_length = collatz.length
  biggest = collatz if collatz_length > biggest_length
  binding.pry
end

In this case, I was trying to solve Project Euler problem #14, the Collatz sequence. At some point, I wanted to refactor my Collatz#length method since it was taking FOREVER to get through all one-million items in the array to find the largest sequence.

Man do I love Ruby. By adding just a few words of code, my bad (read: ineffective) use of Pry becomes extremely effective:

GOOD USAGE OF PRY:

1
2
3
4
5
6
(1..10**6).each do |i|
  collatz = Collatz.new(i)
  collatz_length = collatz.length
  biggest = collatz if collatz_length > biggest_length
  binding.pry if i == 100 || i == 1000
end

By adding in this conditional Pry debugger, I’m able to ensure that - as I’m iterating through a gigantic array of a million items - I’m getting the expected Collatz class behavior along the way at or around the one-hundredth & one-thousandth elements, respectively.

conclusion

While this “pro tip” may have been fairly obvious to many of you Rubyists from the get-go, it didn’t occur to me that I could treat binding.pry just like any other method call in Ruby… allowing me to wrap that method call into some conditional logic at runtime.

Thanks for reading!

Using Xcode’s iOS Simulator to Build Your Next Webapp

| Comments

programmers need to be empathic

When building a web application, developers need to be empathetic - that is, they need to be really good at putting themselves in their users’ shoes. And these days, “users” aren’t just sitting in front of a desktop anymore; instead, people take their computers everywhere with them in the form of mobile smartphones.

Are you in a public place? If so, look around. I mean it - really look around. What do you see? Most likely you can see people with heads lowered playing with their mobile phones.

3 quick facts to convince you mobile is f*$%ing important

  • 91% of all people on earth have a mobile phone
  • 56% of people own a smart phone
  • 50% of mobile phone users, use mobile as their primary Internet source

At this point you may be thinking: “True. I should really make sure anything I’m building is intended for use on a smartphone.” Kudos to you. And luckily, many of the most popular web development frameworks are way ahead of you and me in responding to the tectonic mobile shift. Twitter Bootstrap and Zurb Foundation - a pair of front-end (mainly CSS) frameworks - are representative of this shift. Both compete for the title of “most responsive, mobile-friendly framework” and are obsessed with offering frameworks that render beautifully regardless of the size of the computer’s screen.

…but building mobile-first can be annoying.

With this in mind, in order to be an empathetic developer these days, it’s not a bad idea to approach UI/UX with a “mobile-first” mentality. But “testing” your app in a mobile context can be pretty annoying - you need to first constantly be on your phone and using it to experiment with your app (which, if you have an iPhone like me, means goodbye battery); you are always switching back and forth between laptop and mobile device; and finally, you have to either deploy your app earlier than desired or do some extra work to set up localtunnel or ngrok in order to make your localhost server accessible to your external mobile device.

Enter: iOS Simulator, a part of the Xcode development kit.

Screenshot of how I use it.

This little guy solves that laundry list of problems I mentioned earlier:

  1. You never have to use your actual iPhone (preserve that precious battery)
  2. As a result, no more switching back and forth and using your phone for stuff you’d rather be doing in your natural coding environment
  3. No need to deploy early or set up a localtunnel just so you can access your app’s development environment from an iPhone

And the good news keeps coming: for those of you who use Alfred (which should be anyone who spends lots of time on their computer), there’s a workflow to make opening the iOS Simulator extremely fluid, fast and painless:

Visual of using the workflow - so simple!

Here’s a link to where you can find that workflow as well.

goodnight, and good luck

This strategy has saved me lots of time, headache, and - especially - iPhone battery life. But more importantly, using the iOS Simulator has resulted in a more beautiful and responsive web application this time around since I was de facto engaged in the mobile experience from Day 1. (I basically never opened localhost:3000 in my web browser.) I hope you agree:

TextMeLater

Guiding Your Users: Custom Logic in Your Rails Application’s Navbar

| Comments

navbars are important

Real talk: navbars are fantastic. They’re really good at their job, which is providing a constant set of routes to your users to find their way around. No user ever gets lost when there’s a good navbar around to help out.

New Rails projects ship with an application layout (that is, application.html.erb file) that provides an ideal home for our navbar since we want the bar to always be visible at the top of our app, and the application layour is rendered by all views by default.

The problem with navbars is that they typically aren’t very intelligent. For example, when you’re currently viewing a webpage within an application, most of the time the navigation bar does not update to hide that option dynamically. Why, oh why, would you want to click the same link twice? If you feel me on this one, keep reading…

how to make your navigation bars dynamic

I set out to make my navigation bar dynamic (meaning, again, that it would update its contents/links based on which view page the user was currently looking at), and found it was actually pretty straightforward thanks to inheritance in Ruby.

the problem, in words

Abstractly, the goal is to create some object that’s available throughout my application, in all my controllers and views, that will contain the logic and knowledge of the last URL that the user requested. This way, if a user has just clicked, say, “About” on your navigation bar, the next view should not continue to show that link since it’s become redundant.

the solution, in words

I know that every request hitting my application generates a new instance of the controller behind that particular endpoint. I also know that all of my controllers inherit from a master controller of sorts, which is typically ApplicationController in Rails. Therefore, since my other controllers - the ones actually doing the work of passing data between my models and views - inherit directly from ApplicationController, I figured I could write a method there that did some introspection on the most recent ActionDispatch::Request object in order to keep track of the last request’s URL. In code, this strategy looked something like this:

1
2
3
4
5
6
7
8
9
class ApplicationController < ActionController::Base
  private

  def set_current_url
    @current_path = request.path
  end

  # rest of class omitted for brevity
end

So easy! Through this code, I now had access to the @current_path variable that would be available at each point in time within my views. Here is how I made use of that object (which is available via the set_current_path method) in my views in my application layout file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<nav class="navbar navbar-inverse" role="navigation">
  <!-- Brand and toggle get grouped for better mobile display -->
  <div class="navbar-header">

    <% unless @current_path.match(players_path) %>
      <button type="button" class="btn btn-default navbar-btn" data-toggle="collapse" align="center">
         <%= link_to "Ladder Rankings", players_path %>
      </button>
    <% end %>

    <% unless @current_path.match(timer_path) %>
      <button type="button" class="btn btn-default navbar-btn" data-toggle="collapse" align="center">
         <%= link_to "Game Timer", timer_path %>
      </button>
    <% end %>

    <% unless @current_path == challenges_path %>
      <button type="button" class="btn btn-default navbar-btn" data-toggle="collapse" align="center">
         <%= link_to "Battle History", challenges_path %>
      </button>
    <% end %>

    <% unless @current_path == new_challenge_path %>
      <button type="button" class="btn btn-default navbar-btn" data-toggle="collapse" align="center">
         <%= link_to "Record an Outcome", new_challenge_path %>
      </button>
    <% end %>

  </div>
</nav>

Now, my navigation bar updates dynamically, presenting the user only with logical options for their next to-be-viewed page or resource in my application. Fantastic!

Running Simple Test::Unit Specs in Sublime

| Comments

Setting the Stage: Codewars

Codewars is this awesome site where you can learn Ruby or JS by training on “katas” and climbing the ranks of code warriors on the site. The more elegant and efficient your solution to increasingly difficult challenges, the more honor you incur.

I’ve been working through a few on the Ruby side of things, and interestingly enough the Codewars team has built in to the platform their own testing DSL. It’s sort of a mut: they’ve borrowed all the best elements of Ruby’s most popular frameworks, including RSpec, T::U and MiniTest. The result: for every langauga kata set on Codewars, there is a Test class/prototype (I say prototype because of JavaScript’s unique twist on object-orientation and inheritance). Users can then easily design their own tests as instances of this parent class by invoking very natural-sounding methods like ‘expect’ (from RSpec), ‘assert_equal’ (from T::U), and so on.

the path to enlightenment was winding

Now while that sounds straightforward enough, I must confess it took me a solid couple of hours to realize that Codewars was not using a native Ruby test framework, but rather was utilizing their own testing API (and not just using some built-in T::U syntactic sugar or something):

1
2
3
4
# Create your own tests here. These are some of the methods available:
#  Test.expect(boolean, [optional] message) 
#  Test.assert_equals(actual, expected, [optional] message)
#  Test.assert_not_equals(actual, expected, [optional] message) 

Here’s the docs for the Ruby Test methods that are provided by Codewars’ API. Pretty fancy, huh?

simpler route: use RSpec, even for miniscule test suites

While I appreciate the work the Codewars guys have done on this Test module, I don’t think learning yet another testing DSL (even though it’s only slightly different from RSpec) makes any sense. I’m actually a little confused as to why they would implement their own test framework in lieu of one of the already-accepted and ubiquitous frameworks like RSpec.

I prefer to do as close to 100% of my code-writing in Sublime as possible (practice makes perfect, ya’ know?)

Ruby’s String Interpolation: Syntactic Sugar to the Max

| Comments

there ain’t no such thing as magic

One thing I’ve come to realize about programming - despite almost every gut reaction to the contrary - is that there is no magic. None. Period. Fullstop. As Avi would remind us, Ruby (ignoring that whole C thing) can be distilled into three things: objects, methods, and keywords. So when you see some magic, investigate further, keeping in mind those 3 fundamental components of the Ruby language.

But as I’ve gotten more and more exposure to Ruby’s hidden secrets, it’s become seemingly more difficult to believe there’s no magic going on! This is because Ruby makes use of an idea called “syntactic sugar”. Syntactic sugar is basically a group of special programmatic syntax rules that let you write your code in a way that doesn’t appear to jive with the normal rules of the language, but that is easier to remember how to do and looks better.

syntactic sugar = delicious but disorienting

Syntactic sugar is therefore a vehicle for abstraction. Instead of adhering only to the native syntax rules of the language, Ruby has embraced natural syntactical shortcuts that appear to break the rules, but actually make your code read more legible and human-friendly.

For the most part, syntactic sugar is a wonderful thing. (With a name like that, how could it not be a good thing?!) But it can also be a trifle dangerous without at least a cursory knowledge of what exactly the sugar is coating. Let’s look at a specific example: string interpolation in Ruby.

1
2
3
4
5
6
7
8
9
10
def interpolate_two_variables(num1, num2)
  puts num1.class
  puts num2.class
  "String interpolation allows us to magically include variables, like #{num1} and #{num2}!"
end

interpolate_two_variables(6, 23)
Fixnum
Fixnum
=> "String interpolation allows us to magically include variables, like 6 and 23!"

Sweet, thanks Ruby! I use string interpolation just about every day coding in Ruby - it’s an incredibly powerful and convenient way to group different objects together in the context of, say, a view page in a web app. But… what’s really going on here? I don’t see anything like Ruby’s normal object.method_call syntax, and yet it feels like there MUST be a method call being invoked inside the double quotes. What exactly is the interpreter converting the #{} syntax into?

#{}: more than just a pretty face

Assuredly, there’s nothing magical going on here. Upon being invoked, our friend #{} sets to work telling the Ruby interpreter to call the to_s method on the object inside of itself. In the above example, those objects are num1 and num2. Cool!

customizing our syntactic sugar: DateTime’z

This story has only just begun, y’all. Since Ruby is so awesome, we can of course (re-)define the to_s method at the Class level of our choosing. Consider instances of the DateTime class. I would like for string interpolation of DateTime instances to show up nice and legible - you know, like the way we normally communicate dates and times.

1
2
"#{DateTime.now}"
=> "2013-10-30T12:39:02-04:00"

Hmm… gross. Parsing that mentally has taken me well over the 1 microsecond that I’ve allotted for that task. In true Ruby fashion, let’s dive into DateTime’s to_s method and re-write it for the task at hand:

1
2
3
4
5
6
7
8
9
class DateTime
  def to_s
    self.strftime("The date is %m/%d/%y, and the time is %r")
    puts "Look! \#{} is just calling DateTime#to_s, which we overwrote to make our DateTime objects easier to read!"
  end
end
"#{DateTime.now}"
# Look! #{} is just calling DateTime#to_s, which we overwrote to make our DateTime objects easier to read!
=> "The date is 10/30/13, and the time is 01:31:15 PM"

This example demonstrates that the #{} is merely syntactic sugar that calls the to_s method as defined in the receiving object’s class.

1
2
3
4
5
apples = 4
puts "I have #{apples} apples"
puts "I have %s apples" % apples
# I have 4 apples
=> nil

main takeaways

Going forward, I intend to dive head-first into every example of syntactic sugar that I can get my eyeballs on, because the sugar always coats a delicious candy core of Ruby awesomeness.

HTTPrime: What Can We Learn About Http Request-Response From a Steakhouse?

| Comments

why must an http request be so confusing?!

Look, we’ve all been there. When first setting out to learn about the Great Internets, one of the first themes you’ll come across is that of the HTTP request. You’ll quickly learn that HTTP stands for “Hypertext Transfer Protocol”. And after mulling that over a bit, your next thought might be: “Cool, that wasn’t so hard!” But soon, someone starts throwing new ideas and concepts your way - using words like “server”, “web application”, “controllers”, “get” and “post”. And before you know it, you’re swimming in a sea of disconnected semantic meaning. Bummer.

As it turns out, the Internet is a giant, teeming and conscious (no?) mass of computers which pass long strings of text back and forth, all the time. Now, for the next part of this blog post, I could show you a picture like the following and begin to dissect it, piece by piece:

Alt text

bring on the metaphors!

But I’m not going to subject you to that, dear reader. Today, during an impromptu mid-day comedic improvisation seminar at school (yes, Flatiron School is awesome, we know), we heard about the importance of explaining big, complicated ideas by making comparisons to things that are already understood. (That is to say, we should use more metaphors and analogies.) So instead of telling you everything there is to know about an HTTP request/response cycle, I’m going to offer an intentionally over-simplified story for you wrapped in a familiar metaphorical context: that of a dining experience at a steakhouse.

Note: I’ll be taking a tad of creative license in the coming paragraphs; turn back now if this frightens you or if you can’t bear the idea of a steakhouse experience being in any way misrepresented.

HTTPrime Steakhouse

customers are like clients, and the maître d’ is like a server

First, let’s set the stage. At our restaurant - the HTTPrime Steakhouse - each hopeful customer represents what’s called a client. The client carries with it a very valuable thing: knowledge of what it wants! Much in the way that you enter a restaurant with knowledge of what you expect to order, an HTTP client brings that same information to a web application’s server. In the HTTP world, all clients’ requests arrive at something called a server, which is akin to the gatekeeping maître d’ at our steakhouse. Our maître d’ is responsible for intercepting potential diners, having a quick, formal chat with them to understand what they desire, and handing their request off in the appropriate manner (typically to the restaurant itself at that point, the part where customers sit and dine). I say “formal” chat because, in fact, the server is only able to respond with a particular type of response - integer values communicating whether the client’s request was valid, erroneous, or misguided. Think of how a real-life maître d’ feels a bit stiff when you’re talking with him…

It turns out, this is very similar to the role a web server plays - the server stands at the entrance to the web application (that is, the restaurant itself), has a quick chat with incoming customers (that is, incoming HTTP requests made by clients), and passes the customers with their requests along to the waitstaff and the restaurant itself (that is, sends the HTTP request and its information along to the web application itself).

GET vs. POST

“But what’s all this jazz I keep hearing about GET and POST requests, huh?” Great, great question. You, the client (or customer at HTTPrime, for our purposes) can actually have two types of conversations with our maître d’:

  1. Client: “Hello sir! Could we please be seated, take a look at the menu, and GET some of your delicious filet mignon?”
  2. Client: “Hello sir! I have a delicious filet mignon recipe to give to HTTPrime. Here you go. Maybe you could POST it up in your kitchen somewhere… that way your restaurant will have it available for all future customers.”

A GET request is akin to walking up to the maître d’ and telling him you would like a filet mignon. A POST request is akin to walk up to the maître d’ and telling him you have an amazing recipe for filet mignon, and you’d like to give it to the restaurant. The maître d’ then simply responds to your request by telling you whether the restaurant is prepared to handle your request.

mvc… wtf?

Alt text

waiters are your application’s controllers…

You just wrapped up your chat with our faithful maître d’. You’ve explained you are here to GET (should I stop capitalizing, have I driven that point home yet?) one of HTTPrime’s famous filet mignons. What happens next: magically, out of nowhere seemingly, he summons HTTPrime’s filet-mignon-dedicated who ushers you to your table. Let’s call this waiter boy Rodrigo, because I think that’s a cool name. In web applications, controllers take on the function of a restaurant’s wait staff: they don’t do any of the cooking, nor the cleaning up. All they do is take orders from customers, relay those orders to the kitchen (where the real magic happens), and return to the customer’s side to fulfill their original request. I don’t mean to trivialize the role of a good waiter - after all, bad service is almost as bad as Armageddon itself - so you can see why lightning fast, responsive controllers are a must.

and the kitchen represents your application’s models

Loyal, kind, loving Rodrigo - what a big heart he has - has just confirmed your order to GET (wink, wink) a 3-pound, “rare plus” filet mignon. Where’s he off to next? He’s going to control that order straight over to the kitchen, of course! And as alluded to, this is where the real magic happens. In the kitchen, raw ingredients, spices, and some black magic come together to create HTTPrime’s signature dishes - the ones that people keep comin’ back for. In a web application, the models gather raw data from the database (or other data repository), sprinkle in their own sugar/spice/black magic combination (we call this “logic”, generally speaking), and - voilà! - pass off a perfectly cooked, delicious filet mignon for Rodrigo to satisfy you, the client’s, picky demands.

but wait, it goes deeper - down to the database

But where do these raw materials come from, exactly? Well, in HTTPrime, the raw ingredients used by the kitchen would need to come from at least a couple places. (Good news: more metaphors coming!)

Every time the chef walks down to the basement where all those massive refrigerators chock full of dead animal are kept, he’s essentially accessing our web application’s database. Now, some fancy stuff happens in the database. And frankly, our kitchen chefs don’t understand a lick about butchering cows, packaging the meats, and selling the raw steaks to artery-clogging steakhouse chains like ours (i.e. they don’t speak SQL). But that’s okay, because that isn’t their job.

There’s another way to get foodstuffs into our restaurant. If our steak database is missing some important ingredient - say, cream for the creamed spinach (my mouth is watering) - our team of chefs can go out into the world and grab the missing item from, well, anywhere. We call this “scraping”, and it’s an incredibly handy tool that web developers use for getting data wherever it may be presented on the Internets. For our purposes, just keep in mind that scraping is just another way to get raw ingredients and cooking supplies into our kitchen.

…and the filet’s presentation (you know, garnish and stuff) is like the application’s views

Faithful Rodrigo has just received your freshly prepared filet from HTTPrime’s kitchen, and he’s heading back to where you’re seated in the restaurant. But there’s one problem: you, the client, are extraordinarily picky. In fact, you won’t even look at a filet mignon that you’ve ordered unless it’s plated, garnished, and has a cherry on top. So what’s Rodrigo to do? Well, he makes a quick pit stop at one of those waiter stations they have at fancy restaurants like HTTPrime and dresses up your filet. Literally. He puts the food-equivalent of fancy clothing on your hunk of cow.

Turns out, a web app’s views are also responsible for “dressing up” the content that’s delivered back to the client. Their job is to receive, via our controllers, an object (the important stuff) created by our models and make it extremely presentable. Because, after all, presentation is key - here’s proof:

Alt text

what about the HTTP response, the back half of the request-response cycle?

Actually, this component flows naturally based on what we’ve just understood about the MVC workflow. When the waiter (our application’s controller) finally delivers the garnished, beautified filet mignon to your table, your initial HTTP request has been fully handled and the application is issuing its response! As soon as the waiter removes his hand from the plated filet mignon and sets it before you, the request-response cycle has been completed.

wrapping it up

Well, that concludes this seemingly endless cycle of metaphors in metaphors inside of other metaphors. I hope this semi-realistic real-world analogy has been helpful in understanding the basic flow pattern of an HTTP request-response cycle.

Bon HTTP-pétit!

What Exactly Is Between Those Pipes?

| Comments

“I’ve seen these pipe things before… a bunch of times.” (The thought you just had.)

They look super familiar. Why does Ruby make use of them? What’s inside the pipes?!

Well in short, Ruby reads the thing between the pipes as a local variable to be used in the subsequent block. Let’s look at an example of an iterator (followed by a block) from the Ruby docs.

1
2
3
@names.each do |name|
  puts "Hello #{name}!" 
end

To paraphrase the docs: each is a method that accepts a block of code then runs that block of code for every element in a list, and the bit between do and end is just such a block. The thing between pipe characters is the parameter for this block.

What happens here is that for every entry in a list (i.e. @names in this example), name is bound to that list element, and then the expression puts "Hello #{name}!" is run with that name.

(Thought tangent: So this example actually points to another cool feature of Ruby - “duck typing”. When we see @names.each, we naturally expect @names to be an Array (or Hash) and we’ll be iterating over each element. But not so fast! What happens if @names is actually something totally different - like, say, an object from a custom-built class called Names? Warning: this is a highly contrived exmaple…)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Name
  attr_accessor :string
  def initialize(string)
    @string = string
  end
  def each
    self.string
  end
end

@names = Name.new("woe, this is weird - I'm a psuedo string attr within a Name object which responds to #each?!")
@names.each do |name|
  puts "Hello #{name}"
end
=> "woe, this is weird - I'm a psuedo string within a Name object that responds to #each?!"

(Um, pretty awesome, right? Ruby doesn’t care about what you expect it to do; it only cares it the object at hand responds to the method being called. Talk about an egalitarian language!)

Now that we’ve had an intro-duck-tion to blocks and pipes, here’s a question - how would you define the thing between the “pipes” (these guys: || ) in the following code example:

1
2
wrecking_ball = Song.new
wrecking_ball.tap { |song| song.name = "Wrecking Ball" }

(Another mental tangent: I think pretty much every object responds to #tap - that will have to be for another blog post though.)

To put the question differently, what’s the |song|? No, seriously - what is it?! Multiple choice:

  • (a) method
  • (b) keyword
  • (c) variable

If you guessed C then you were spot on - pat yourself on the back! To be more specific, that thing between the pipes that we see in almost every block is actually a local variable. This is Ruby’s approach to getting the object receiving the method call (e.g. the wrecking_ball Song object receiving the tap method) inside the method as an argument. The convo with Ruby (since we all have dialogues with our computers in the language of Ruby these days) goes down something like this:

“Ok lord programmer, I realize you’re calling a method on this object - and you’re hoping to “`yield“` the object receiving the method call to the method’s block (the code following the “`.each do “` bit). Tell ya’ what: in order to make sure said object gets from the left side of this expression into the yielded block, I’m going to temporarily make a local variable - you can even name it WHATEVER YOU WANT - so that you have full access to the object within the block. Sound good? You bet your ass it does. I’m Ruby, we’re gonna’ get along famously.”

Putting down the pipe (only temorarily, calm down)

Awesome. Now we know exactly what’s going on between those pipes. Ruby is creating a local variable that points to the object receiving the method call, all so that we can fully access our object inside the method’s block. Thanks Ruby.

To drive this point home, let’s remove these pipe thingies and see if we can still code like we normally do.

1
2
3
4
5
6
7
8
9
10
some_numbers = [5,6,7,8]
some_numbers.collect do
  puts "This is our block!"
end

"This is our block!"
"This is our block!"
"This is our block!"
"This is our block!"
=> [nil,nil,nil,nil]

OK, so that’s pretty interesting. It looks like our block is definitely being evaluated, and our collect iterator is yielding to that block precisely self.size times (or 4 in this case). Since we have a puts method, whose return value is always nil, we end up with the returned array of nil’s above. But I want access to the [5,6,7,8] on which we’re calling .collect! Let’s try another strategy:

1
2
3
4
5
6
7
8
some_numbers.collect do
  p some_numbers
end
[5, 6, 7, 8]
[5, 6, 7, 8]
[5, 6, 7, 8]
[5, 6, 7, 8]
 => [[5, 6, 7, 8], [5, 6, 7, 8], [5, 6, 7, 8], [5, 6, 7, 8]]

Alright, getting closer. Looks like we still have access to the entire object receiving the .collect method call. How can we get to one element of some_numbers at a time though? In other words, how can we get specific, granular access to each component of the object at hand, the one receiving the method call? How can we have our block be evaluated on each element of some_numbers, but only one element at a time? The answer lies in Ruby’s implementation of Array#each (and really all the iterators) - here are implementations we’ve written @flatironschool:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Array
  def each
    i = 0
    while i < self.length
      yield(self[i])
      i += 1
    end
    self
  end
  def my_each_with_index
    i = 0
    while i < self.length
      yield(self[i], i)
      i += 1
    end
    self
  end
end
some_numbers = [5,6,7,8]
some_numbers.my_each_with_index do |x, i|
  puts "At index #{i} the value is #{x}"
end
At index 0 the value is 5
At index 1 the value is 6
At index 2 the value is 7
At index 3 the value is 8
=> [5, 6, 7, 8]

Lines 5 and 13, there’s our old pal yield. How cool it is to finally see the distinction between .each and .each_with_index - it’s merely the # of local variables from self (the object, in our case the Array [5,6,7,8] receiving the method call) that we “yield” or pass along to the block! Now, finally, we having a working definition of what’s betweeen the pipes: they demarcate local variables which represent each element of self that get passed to the block each time our method call yields to the block!

In my next post, I want to talk about Ruby’s bindings - a poorly understood (and rarely needed) aspect of Ruby that I hope to shed some light on.

Until then: #workhard, #benice!

A Short & Sweet Intro to Objects in Ruby

| Comments

Recently here at Flatiron we’ve begun to write our code with a focus on object orientation. To a beginner, this sentence has absolutely zero meaning whatsoever - so let’s take a step back and define some terms.

First of all, there are a couple truisms to keep in mind when it comes to code:

  • First, in case you haven’t heard yet, things are going to change. Your application will grow in users; new technologies will emerge; your investors will want you to add new features (talk about a first world problem!). Your code base needs to be flexible when it comes to making changes for any of these reasons - flexible like a reed in the wind, as opposed to brittle like, say, graphite. As Sandi Metz puts it:
    Changing requirements are the programming equivalent of friction and gravity.


Ok, great! So we know change is a-comin’. How do we structure our code to be prepared like the Boy Scouts?

  • The less the different segments of your code base know about one another, the better! Admittedly, this one is a bit counterintuitive. In life, we’re typically used to setting all of our ducks in a row before taking any major steps or jumping off any cliffs (figuratively speaking, for the most part). We’re naturally pretty risk averse, and we routinely succumb to the delusion that we can mitigate risk and uncertainty a bit by lining up said ducks. It’s as if we’re trying to tear the mask of the unknown off so that we can make decisions today with perfect information. Programmers have adopted a different approach: instead of trying to know and discount the future, they simply design programs that will adapt easily, fullstop. Note I’ve made no assumption about what changes will emerge to throw our programs for a loop; the emphasis is on a coding paradigm in which your different segments can easily change how they communicate with one another. This is what people mean when they talk about the principle of object-oriented design. Once again, let’s get Sandi’s take:
    In the absence of design, unmanaged dependencies wreak havoc because objects know too muchabout one another. Changing one object forces change upon its collaborators, whichin turn, forces change upon its collaborators, ad infinitum.

Now let’s take a look at some code. Let’s try to build a bicycle in Ruby - first we’ll eschew the object-oriented princples just discussed, and then we’ll embrace them. Hopefully the proof is in the pudding!

First, the painful, hard-to-read & -follow version…

Whew, that was pretty exhausting and hard to follow. Let’s see what happens if we segregate along natural, real-world dividing lines…

2 Reasons Why Larry Wall Is the Man

| Comments

  1. He says things like this in speeches that are ostensibly about Perl but really are about postmodernist culture and life:
    True greatness is measured by how much freedom you give to others, not by how much you can coerce others to do what you want.
  2. He has 4 extremely intelligent children, one of whom is a postdoctorate student in physics studying BLACK HOLES.
  3. And on that second point: his son’s name is Aron Wall, and he wrote this highly readable primer on black holes - what they really are, why light can’t escape (hint: it’s because once you/anything crosses the event horizon, the black hole moves AWAY FROM YOU/ANYTHING AT THE SPEED OF LIGHT OMFGGGGG!!!), and why they portend the next massive revolution of thought in theoretical physics as we know it.

    Whew.

    Thanks Larry Wall. You’re a real mensch.

Scope in Ruby Is Like a Cell Membrane

| Comments

How is program scope like a cell membrane?

Scope is the context within which something is defined. Let’s focus on methods, for starters. If you write a page of code with a method in it, alongside a bunch of other stuff (variable declarations, enumerators/iterators not contained in that method, etc.), don’t expect your method to have any clue what’s going on above or below it in that page. Sorry, that explanation sucked - let me show an example:

some_numbers = [1,2,3,4,5]
another_variable = {:cell_membrane => "cytosol", :receptor => "ligand"}
more_variables = some_numbers.collect do |num|
    num * 2
end

def method_in_same_code_file(args)
    more_variables + some_numbers ##=> This method doesn't know what these are!! 
end

The way that we get around this issue of restrictive method scope in Ruby’s design is actually something we all are quite familiar with: passing arguments to our methods. Perhaps you can imagine now the similarity to a cell membrane - take a look at the image below. I would sa the receptor-ligand binding is a lot like doing something like this:

<page of code omitted… let's just call the method>
method_in_same_code_file(some_numbers, more_variables)

In this method call, our arguments works just like our receptor-ligand binding! Put differently: the arguments function as the cell membrane’s receptors, in that only by going through them can stuff on the outside be itelligible/readable to the method’s insides.

Method scope visualization!

cool things Kent Beck has said (about programming):

One line methods are there to communicate.

You don’t spend three or four lines expressing iteration, you spend one word.

YAGNI: You aren’t going to need it.

Optimism is an occupational hazard of programming; feedback is the treatment.

(Speaking about his Chrysler experience…) By far the dominant reason for not releasing sooner was a reluctance to trade the dream of success for the reality of feedback.

Make it work, make it right, make it fast.

how to write a basic test/spec:

def assert_equal(actual, expected)
    unless actual == expected
        puts "fail: expected #{expected} but got #{actual}"
    end
end

Not so bad, right?