How to write a switch statement in ruby

case a  
when 1..10  
  puts "It's between 1 and 10"
when 8  
  puts "It's 8"
when String  
  puts "You passed a string"
else  
  puts "You gave me #{a} -- I have no idea what to do with that."
end 

Programming languages are very similar to spoken languages. One of the closest similarities is the translation of certain words or concepts from language to language.

In English we say “Hello” while a Spanish speaking person might say “Hola”. Generally these two definitions mean same thing and are direct translations of each other. With programming languages there are also certain concepts and definitions which are translatable from one language to the other.

I have a friend that codes in ActionSCript and he has been very helpful when I get stuck on a problem or concept in Ruby. It amazes me that he is just as able to solve a problem based in Ruby by looking at it through the eyes of his chosen language, ActionScript. Additionally a lot of times the code looks so similar that I can understand the flow even though I do not know the intricacies of ActionScript itself.

I’m finding that programming constructs are generally the same from language to language. There are certainly subtle differences between languages but the basic methods, ideas and definitions do not change much.

Last night I was working on a problem that matched round, square and curly braces. I was given an array which held string expressions of braces. A matched brace meant that the round, square and curly braces all closed perfect. As an example “([])” would be a matched brace but “[(])” would not.

I was able to setup the initial flow of the problem but got a little stuck when trying to compare the matched braces within each other. I showed the problem to my friend and he was able to come up with a solution using a switch statement. I searched online for the equivalent switch statement in Ruby and found it was the case statement. I had seen it before but never really used it extensively. It’s really useful because you can match objects to the case statement then perform an operation if it is an exact match (a == 1..10). This saves lines and times without having to write numerous if, elsif and else statements.

Using the case statement I was able to solve the problem and now have a handy new weapon in my coding arsenal. I’m going to train very hard over the next few weeks and I think I’ll be battle ready very soon.

Advertisements

Hash Browns

person 1 = { first: "Papa", last: "Jah" }  
{:first=>"Papa", :last=>"Jah"} 
person 2 = { first: "Mama", last: "Jah" }  
{:first=>"Mama", :last=>"Jah"} 
person 3 = { first: "Jah", last: "Jah" }  
{:first=>"Jah", :last=>"Jah"} 

params = { father: person1, mother: person2, child: person3 }  
{:father=>{:first=>"Papa", :last=>"Jah"}, :mother=>{:first=>"Mama", :last=>"Jah"}, :child=>{:first=>"Jah", :last=>"Jah"}} 

params[:father][:first]  # verify it has the right value  
=> "Papa"

Working with rails you will see a lot of hashes. It’s an efficient way to store data from your web application in a particular way. A common example where you would use a hash in your application is in the collection of user data that you have for your website.

When users sign up for your website you will undoubtedly collect a heap of information regarding that particular person. Name, address, email, telephone number, gender, date of birth and the list goes on. Some of this data will be numeric, alphabetic and alphanumeric so you need a cohesive way to store this relevant data for each person.

Hashes allow you to do that by creating a “hash” with information that is specific to each user/ID. As seen in my example above I initially created three separate hashes called person1, person2 and person3. I combined this hash into one has called “params” which can be described as my family hash with father/mother/child all being associated to the relevant individual hashes. I can now access this data very easily by pointing the key-value relationship of the hash. E.g. if I wanted to see my father’s first name I would type:

params[:father][:first] (as shown above).

There are 3 different ways you can create a hash:

#1. Create an empty hash first using the curly "{}" bracks
user = {}  
user[:first] = "Papa" #associating the symbol :first to the string "Papa"  
user[:last] = "Jah" #associating the symbol :last to the string "Jah"  
#2. Use the hash rocket directly "=>"
user = { :first => "Papa", :last => "Jah"}  
#3. Use special Rails notation for hash assignments
user = { first: "Papa", last: "Jah" }*  

Using a hash you can efficiently store varying types of data to a unique person or ID. It’s important to note that order does not matter in a hash. If you have a data set that requires ordering then a better tool to use would be an array.

*The spaces between the curly brackets are not necessary but generally used by the rails community

How to add date/time created to your Ruby on Rails application

<p>  
  <h1><%= @article.title %></h1>
</p>  
<p>  
  Posted by:
  <strong><%= current_user.email%></strong>
</p>  
<p>  
  On<%= @article.created_at.strftime("%B %d %Y, %l:%M%P") %>
</p>  
<p>  
  <h4><%= @article.text %></h4>
</p> 

After a good time spent searching how to do this online, I thought it would be helpful to write a blog post about it.

I am building a message board using rails and I wanted to add the date/time a post was created on the site. E.g. when a user creates a new post, the date and time that post was entered into the database should show on the page.

To do this we can use a rails built-in method called “createdat”. In the above example I have a snapshot of my codebase in the show.html.erb file. In order to show the date/time created I called the “createdat” method on an instance of my @article class which contains all of the posts for each user. However, this will output the date/time in a pretty ugly format: ‘2013–04–20 01:32:11 UTC’.

You can use the “strftime” method to show the date/time in a more readable format. The strftime formats can be found here.

Enjoy!

List of sublime text shortcuts, tips and tricks

I started using sublime text over the past couple months (RIP textmate) and it’s been awesome so far. I wanted to create a short list of the shortcuts, tips and tricks that I’ve found most useful:

Files
cmd+p — Go to Anything
cmd+ctrl+p — Switch Project

Codes
cmd+shift+d — Duplicate Line
ctrl+enter — Insert line after
ctrl+shift+enter — Insert line before
cmd+l — Expand Selection to Line
ctrl+shift+w — Wrap Selection with Tag
ctrl+r — Go to symbols (finding methods)

Multi Edits
ctrl+d — Select the current word and the next same word
ctrl+click — Every place you click will create a cursor to edit
ctrl+shift+f AND alt+enter — Find a word in your files and then select them all
ctrl+] — Indent
ctrl+[ — Unindent
Ctrl+Shift+UP — Move lines up
Ctrl+Shift+Down — Move lines down

Multi Selection
To enable multi-selection, you have several options:

Alt or Command — then click in each region where you require a cursor.
Select a block of lines, and then press Shift + Command + L.
Place the cursor over a particular word, and press Control/Command + D repeatedly to select additional occurrences of that word.
Alternatively, add an additional cursor at all occurrences of a word by typing Alt+F3 on Windows, or Ctrl+Command+G on the Mac. Amazing!! <span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Refactoring your code

There was once a time when I had a deep affection for mathematics. I think we fell apart sometime during college but my quest to learn programming has renewed this relationship.

A major concept in computer science that I’m still getting a hang of is refactoring. It’s very similar to factorization in mathematics where you have an expression that you want to reduce to “basic building blocks”. E.g. if “x = a + b + c” and “y = a + b” then you can factor “x = y + c”.

This same concept lends itself to computer programming by the name of refactoring. Similarly this process involves rearranging a program to facilitate code re-use and improve the readability of your code.

Here’s an example from today. I’m working on a procedure “addpageto_index” that takes three inputs and updates the index to include all of the words found in the page content by adding the url to the associated word’s url list. If that’s a little confusing (or worded terribly) this problem set is one of many on the way to building a search engine. In this example I am looking for some content (word) and want to find all the url links associated with that word:

index = []

def add_to_index(index,keyword,url):
    for entry in index:
        if entry[0] == keyword:
            entry[1].append(url)
            return
    index.append([keyword,[url]])

def add_page_to_index(index,url,content):
    a = content.split()
    #print a
    for word in a:
        for entry in index:
            if entry[0] == word:
                entry[1].append(url)
                return
        index.append([word,[url]])

add_page_to_index(index,'fake.text',"This is a test")
print index

The previous problem was already used to find a procedure that adds keywords to an index with their associated urls, “addtoindex” (which is the first part of the above code). I initially started this problem by rewriting the first part to include the “content” or words in the second part.

After some initial trial and error the second part of my code looked like this:

def add_page_to_index(index,url,content):
    a = content.split()
    #print a
    for word in a:
        add_to_index(index,word,url)<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Unbeknownst to me I should have just used refactoring the whole time as I already had written what was needed previously. Eventually I saw that I could refactor the code and was able to solve the problem. I still feel very new to this but it gets me excited every time I notice small things like that. I think I’m slowly getting there.

Building a Rails 4 app using the Twilio API

This weekend I wanted to challenge myself by building a functional web application using the rails framework. My goal for this project was to use an API that I was unfamiliar with and that could be used from my iPhone.

I settled on the Twilio API. Twilio is a company who services voice calling and SMS messaging integration into your app. On the messaging side the service works by essentially turning all text messages into a RESTful architecture. By utilizing a RESTful architecture for your incoming/outgoing SMS requests, you are able to map those requests to the routes in your rails application.

Behind the scenes Twilio figures out how to handle your app requests by using a construct known as webhooks. This is done for you on Twilio’s side. When someone makes a request to your twilio number, either by phone or SMS message. The webhook which is simply an URL will handle that request and follow the directions you give it to make a follow up call or text message.

The entire process of putting this app together was a very frustrating but tremendous learning experience. From a technical standpoint the actual code was not that difficult. The most challenging part was configuring my rails app to talk with Twilio.

You have to very, very RESTful minded when integrating Twilio into Rails. As I’ve gone through this journey I wanted to put together a step-by-step tutorial to make it easier for the wider developer community:

1 Create a Twilio account

First sign up for a Twilio developer account. The account is free and you will be given a certain amount of credit ($$$) to use on your account.

Remember that Twilio actually sends out SMS messages and/or voice calls which does cost money. (A simple google search will help you to find coupons that you can use to add more credit to your account, especially if you’re a student!)

2 Configure your account

During sign up Twilio will either send you a text message or a quick phone call to make sure you are not a spambot. We all hate those now don’t we?
Input the verification code and then proceed to getting your phone number.

3 Choose a phone number

Next get your Twilio number. This is a unique phone number given to you by Twilio which will allow you access to their voice calling and SMS messaging capabilities for the API.

Twilio will assign you a random phone number but you can choose your own based on your location.

4 Add Twilio to your new Rails 4 app

Start up your rails new app

rails new twilio-messages

Add the twilio gem to your Gemfile

gem 'twilio-ruby'

5 Add your aunthentication keys

You can find your authentication keys on your Twilio dev account. You will need both the accountsid and authtoken. For example let’s say you wanted to show all incoming text messages on your rails view.

# messages_controller.rb

class MessagesController &amp;amp;amp;lt; ApplicationController
 def index
  client
 end

 private

 def client
  twilio_phone_number = "9734594512"
  account_sid = 'FDlkje3553l;kj6ljfsafdasf'
  auth_token = 'SFDFAF78987FdfE889'

  # set up a client to talk to the Twilio REST API
  @client = Twilio::REST::Client.new account_sid, auth_token
 end
end

Then in your view:

<h1>Lauryn</h1>
<% @client.account.messages.list({}).each do |message| %>
<ul>
 <li><%= message.body %></li>
</ul>
<% end %> 

6 Test your app locally with ngrok

Since Twilio is looking for a live GET/POST request from your app you will not be able to integrate Twilio on localhost:3000 alone. You can use the ngrok gem which essentially creates a live webserver on the internet for your gem so that you can test it locally.

Gem here

7 configure your incoming/outgoing routes

This is how your app will retrieve data from Twilio and then process the incoming or outgoing requests. You MUST make sure that your controller#action matches what you have on your Twilio dev account.

Rails.application.routes.draw do
 resources :messages
 get '/incoming', to: 'incoming#send_message'

 root 'messages#index'

8 Handle incoming SMS and replying

Twilio allows you to handle incoming SMS messages and then reply to them based on their given body. Twilio uses a special XML format called TwiML that turns the SMS message into a hash containing a lot of data. You can use params[:Body] to respond to a given SMS through your matching controller#action.

# incoming_controller.rb

class IncomingController &amp;amp;lt; ApplicationController 
 def send_message
  body = params[:Body]

  @twiml = Twilio::TwiML::Response.new do |r|
   if body == "Lauryn, what is my current location?"
    r.Message "Ready Or Not, Here I Come, You Can't Hide.
Gonna Find You and Take it Slowly" 
   else
    r.Message "You might win some but you just lost one"
   end
   # r.Message "What up bruh."
  end

  render 'send_message.xml.erb', :content_type =&amp;amp;gt; 'text/xml'
 end

end

Then make your relevant route using an XML view:

#send_message.xml.erb

<Response>
 <Sms><%= @twiml.text %></Sms>
</Response>

9 Change url to your server

Make sure your SMS url is set to GET and that it matches the same URL in your route.

10 Getting puma/postgres/heroku up and running

You will probably want to have your app go live on the internet. Heroku is a good server that you can use. For your first time: YOU WILL GET FRUSTRATED. Make sure you read the docs.

heroku logs tells you nothing heroku run rails console is okay heroku logs is your best friend

11 Finally here are some final pointers in deploying:

Remember to always be pushing to heroku, some of your app updates might not get reflected in Twilio.

rails c = app.class

Do not name your methods reserve words like send

Twilio methods are case sensitive
Twilio::Twiml != Twilio::TwiML
Twilio::Rest::Client != Twilio::REST::Client

12 rails is convention over configuration

= goes out the window when using APIs

Object feels and introspection

One of the most interesting concepts I’ve learned so far about the Ruby programming language is the idea of introspection. In computing, type introspection is the idea that an object or program knows about it’s own properties at runtime.

Specifically in regards to Ruby this means that an object is self-aware and knows what it is, what values it contains and what’s going on around it at a given moment in time. In short, Ruby objects can have feels.

Similar to our good friend Keanu, a Ruby object can have a moment of reflection at a given moment in time. Let us make code:


x = "hello world"
x.class #=> String

x = :hello_world
x.class #=> Symbol

This is a relatively straightforward example that shows how Ruby is able to reflect on itself at two separate moments in life. We can ask Ruby what type of object it is, what type of methods we can call it and then infer more information about it’s scope given that information.

 

The importance of introspection

At this moment you’re probably asking yourself a number of questions.
What’s the big deal? Who cares if “Hello World”.is_a?(String) knows that it’s a string. It doesn’t seem all that complex or exciting.

WRONG.

Although by nature it’s a relatively simple concept, the building blocks that introspection provides come together to form the Voltron that is object orientation. The building blocks of introspection form complexities which allow us to create objects that can interact with each other.

Furthermore, introspection is crucial in our use of mixins, modules and class methods. At the most fundamental level introspection allows us to do all things Ruby and for that we must be forever grateful.


based_god = Class.new
young_based_god = Class.new(based_god)

lil_b = based_god.new
brandon = young_based_god.new

lil_b.instance_of?(based_god) #=> true
brandon.instance_of?(based_god) #=> false
brandon.kind_of?(based_god) #=> true

In our example we create two distinct classes, based_god and young_based_god with based_god being a superclass of young_based_god. We next create two instances of each of these two classes.

Ruby has a method called instanceof? that allows us to check the class of an instance. When comparing both instances we find that only lilb is an instance of the Class based_god.

However, when we use the Ruby method kindof? it is clear that Ruby knows that brandon is a subclass of *basedgod. Through introspection the language implicitly knows that *based_god is a superclass of young_based_god.

The idea of introspection is helpful to us as programmers because we do not have to guess the type of an object. If we want to know what an object is or what methods are available to us to use on that objects we can just ask.

Introspection means that we can make two different objects interact with each other in very unique ways and still be confident that their behavior will do what we expect. It is key to the beauty of Ruby and part of the reason it flows like a natural human language.

Thank you Matz and thank you based god.