Rails and Stuff at Abel killed Cain

Ruby on Rails and other Webdevelopment

Here is a small collection of Tips and Tricks for Ruby in association to Rails.

I will paste some irb-logs, displaying all results.
1. Format decimals or text quickly

In order to display amounts or leading zeros:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>> "%.2f" % 49.4
=> "49.40"
>> "%03d" % 1
=> "001"

# even text:

>> msg = "Welcome, %s";
?> msg % "peter"
=> "Welcome, peter"

# even cooler


>> "<%s> %s </%s>" % %w{strong cool strong}
=> "
<strong> cool </strong>"

Just keep in mind that the result is a String!

2. Using Hash-Keys

1
2
3
>> test = {true => "Yes", false =>"No"}
>> test[ 100 == "foo" ]
=> "No"

3. Mass Assignment

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>> a,b,c,d = 1,2,3,4
=> [1, 2, 3, 4]
>> a
=> 1
>> c
=> 3


# for methonds:

def giveme_five(*hand)  #<-- note the *
      #get fingers
      f1,f2,f3,f4,f5 = hand
end

4.The Ternary Operator
Often its forgotten! Imagine you want to add classes in HAML e.g.

1
>> :class=> current_user ? "active" : nil

5. Use ranges!
Instead of if/else hell, you can use:

1
2
3
4
5
6
7
>> case number
>>       when 0..100: "small"
>>       when 100..200: "medium"
>>       when 200..300: "big"
>>       else "unbeliveable"
>> end
=> "medium"

6. Array.join
* followed by a String can be a shorter way to get the result:

1
2
3
4
5
>> [1,2,3] * 2
=> [1, 2, 3, 1, 2, 3]
# BUT:
>> %w{ruby really rocks} * " - "
=> "ruby - really - rocks"

OC it works with numbers as well.

7. Easy Iteration
Imagine a bad class, giving:

1
2
3
4
5
result = Model.first

# but sometimes:

result = Model.several_rows

Iterating these models is just as easy as:

1
2
3
[*result].each {|r|
      ...
}

Hope this helps someone out.

What are your favorite Tips and Hints?

Write a Comment