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.”
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:
- The first argument is what you want inside the
<a>
tag. For examplelink_to("today's news")
produces<a>today's news</a>
- 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>
- 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.
What is the ./bin directory in a Ruby on Rails project?
Introduced in Rails 4, the ./bin
directory contains your app’s “binstubs.” Binstubs are wrappers around gem executables, like rails
or bundle
, which ensures a gem executable is run inside the correct environment for your Rails app.
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.
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.
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.
How to open the database's CLI in Ruby on Rails
rails dbconsole
Should I use MySQL or PostgreSQL with Ruby on Rails?
PostgreSQL.
(Updated for 2015.)
Using attr_accessor in Rails model classes
- Don’t confuse
attr_accessor
andattr_accessible
– they have very similar names attr_accessor
is a pure Ruby function to create reader and writer methods for an instance variableattr_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 ensure multiple ActiveRecord calls happen sequentially
ActiveRecord::Base.transaction do
savings.withdrawal(100)
checking.deposit(100)
end
If any exceptions are raised, the entire operation is rolled back on the database layer and nothing will be committed to the database.
How to use sshkit in vanilla Ruby (without Rails)
require 'rake'
require 'sshkit'
require 'sshkit/dsl'
# your code goes here
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
Should I use gets.chomp or Readline for user input in Ruby?
Use Readline.readline()
. That’s what irb
uses for user input.
Don’t use gets.chomp
.
How to get rid of control characters like ^[[D in Ruby's gets.chomp
You’re coding some Ruby. You use gets.chomp
to get user input. You run your ruby file. You type some text at the prompt. Looks good, right? But then you press the left arrow key and… ^[[D
appears on the screen. WTF is that?
Should I use Turbolinks in Rails?
No.
(Don’t believe me? Google it.)
How to programatically control Wordpress with Ruby using XML-RPC
This week, I wanted to programatically create posts on my Wordpress site, Maxims. Unfortunately, all of the example code I found online for controlling Wordpress was using PHP, and I hate PHP. I wanted to control Wordpress with Ruby using XML-RPC.
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
Get Safari's Reading List programmatically with Ruby
I wanted to export my Safari Reading List on OS X, so I wrote some code to do it. I leveraged Ruby, but this methodology could be easily ported to other languages like Bash, Python, or Objective C.
How to make a ruby file executable
In the ruby file:
#!/usr/bin/env ruby
puts 'Hello world'
At the command line:
chmod +x ruby.rb
Then you can execute it like this:
./ruby.rb
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.