→ ruby → → →
Problem with MySQL and NULL pointer with ActiveRecord
Today I encountered problem on one of new servers we got, right after migrating application to it. Accessing data using ActiveRecord was failing even with simples statement Model.all. Error was:
Created on 07 July 2009
Sorting objects in array in Ruby
It's easy to sort a simple array in Ruby, you just do a=[1,3,2]; a.sort. But what if you want to sort array of objects? It's also very simple.
All you have to do is define a spaceship operator. What is spaceship operator? It's this: <=>. It returns three values for A and B. -1 if A<B, 0 if A=B and 1 if A>B.
Created on 15 June 2009
Round number to specific number of decimal places in Ruby
The easy way is to extend Float class by adding round_to method with precision parameter.
Created on 16 May 2009
Shoes gem problem?
Once I was trying to use mechanize with Shoes, and all I was getting was a problem with missing mechanize gem. Solution turns out to be pretty simple: You have to install gem in Shoes. To do it, just place this section at the beginning of shoes application:
Created on 15 May 2009
Including module inside module in Ruby
Basically, the question was (yes, sometimes I have doubts): if you include module A inside module B, and you include module B in class, do you have access to methods defined in module A? Or maybe you have to include module A in the class? The simple answer is that you can include module inside module and both modules will be usable from the class at that point. See below:
Created on 14 May 2009
Use inject! Change three lines of code into one! Use inject! Stop repeating yourself!
Which three lines you keep repeating all over again? Initializing variable? Iterating over collection and inserting into that variable? Returning that variable? Do it in one line!
Created on 13 May 2009
Playing with blocks in Ruby, passing blocks, calling blocks
Below is some code that plays with blocks. It shows different methods of passing a block, passing parameter and block, as well as passing variable number of parameters and block. It also shows two different ways of calling a block(using .call and ). Can you predict output of the script?
Created on 12 May 2009
Nice numbers with underscores _ in Ruby
Big numbers in code are not the most readable thing. There's a simple way to improve it. Just use underscores! What is 10000000? It's the same as 10_000_000! As simple as that! Works also with floats. And yes, you could argue that it's the same as 10**7... Let's just quickly see irb output:
Created on 11 May 2009