Posts tagged Ruby

How to rename a hash key in Ruby

Assume you have a Ruby Hash with the regions of the United States:

$ usa_regions
=> {"northeast"=>11, "southeast"=>12, "midwest"=>12, "southwest"=>4, "rest"=>9}

But instead of calling the West the rest, you want to rename it to west.

Here’s how you would do that:

$ usa_regions["west"] = usa_regions.delete("rest")

Now, usa_regions has a hash key named west instead of rest. Importantly, the value of rest – 9 – has been preserved and assigned to west:

$ usa_regions
=> {"northeast"=>11, "southeast"=>12, "midwest"=>12, "southwest"=>4, "west"=>9}

Solution to the "Coin Maker" computer science interview question, using Ruby

A common computer science interview question goes something like this:

“Write a program that makes change with a minimum amount of coins for a given amount – a ‘Coin Maker’, if you will. You have unlimited amount of 1¢, 5¢, 10¢, and 25¢ coins. For example, $2.16 would consist of 8 quarters, 1 dime, 1 nickle, and 1 penny: 11 total coins.”

more...

Rails' link_to always gives me a headache

After 9 years of writing Ruby on Rails code, link_to() never ceases to trip me up. Does it trip you up, too? Here are some quick notes:

  1. The first argument is what you want inside the <a> tag. For example link_to("today's news") produces <a>today's news</a>
  2. The second argument is the href attribute value. For example, link_to("today's news", "www.news.com") produces <a href="www.news.com">today's news</a>
  3. The third argument is a hash that contains everything else – most importantly, your <a> tag attributes. For example, link_to("today's news", "www.news.com", {id: "newsbox", class: "infos"}) produces <a id="newsbox" class="infos" href="www.news.com">today's news</a>. The third argument can contain many other options, of which I have never been able to find a definitive list.

The Ruby on Rails folder structure

When a new Ruby on Rails project is created with rails new, many files and folders are created inside your project folder. Here’s a quick reference of what those are.

more...

How to assign a variable based on a condition in Ruby

If you need to assign a variable based on a conditional, most programmers would do something like this:

result = nil
if condition == true
  result = 1
else
  result = 2
end
puts "The result is {result}."

I usually cringe when people say things like, “Oh, that’s a very C way of doing that”… but in this case, well, that’s a very C way of doing that.

more...

How to list all rake tasks

rake -T -A

This command will print out all available rake tasks. You can use it with Rails' Rakefile, or with a custom Rakefile. N.B.: not all tasks have descriptions, and that is okay.

Using attr_accessor in Rails model classes

  • Don’t confuse attr_accessor and attr_accessible – they have very similar names
  • attr_accessor is a pure Ruby function to create reader and writer methods for an instance variable
  • attr_accessible is a pre-Rails 4 function to list the model attributes (e.g., database fields) that can be set via mass assignment, providing access control

You can use attr_accessor on a Rails model to create non-persisted instance variables. For example:

class Stock
  attr_accessor :current_price
end

This allows you to get the @current_price of a stock – something that would make no sense to persist.

How to put a prompt before gets.chomp in Ruby

Do you want to ask the user for input at the command line, using a slick 1980’s hacker movie prompt like this: >>?

Don’t use gets.chomp. Use readline instead:

require 'readline'
Readline.readline(">>")

…will output:

>> I can write stuff here

How to obtain the number of files in a folder, recursively, using Ruby

I have often found myself wanting to know how many files are in a folder, including files in sub-folders. I whipped up a little Ruby code for just that:

folder_to_count = "/path/to/folder"  # You should change this
begin
  file_count = Dir.glob(File.join(folder_to_count, '**', '*')).select { |file| File.file?(file) }.count
rescue
  puts "ERROR: The number of files could not be obtained"
  # typically occurs if folder_to_count does not exist
end

Creating a ruby launchd task with RVM in OS X

In the last few years, ruby has taken the world by storm. With different projects dependent on different versions of Ruby, many Rails, Jekyll, and Sinatra programmers have installed RVM to manage their ruby versions in OS X. I am one of them.

While RVM is awesome, it can make some previously simple tasks difficult. One such example is creating a launchd daemon that invokes a ruby script. If your gems are installed with RVM, you will need to use RVM to write your daemon. That’s where it gets complicated.

This tutorial teaches you how to schedule a ruby task on OS X using launchd. You can schedule any ruby file to be run. It will be executed using the RVM ruby version of your choice.

more...