Hide Sidebar

Initialize Arguments And Superclass

by Kyle on · Posted in Ruby

The rules are:

super               # passes all arguments
super()             # passes no arguments
super(arg1, arg2)   # passes these explicit arguments

So that:

class Chunk < ActiveRecord::Base  
    def initialize(*args)
        @count = 0
        super
    end
end
 
cnk = Chunk.create(:letter => ?a)

Selecting The Array Index With The Maximum Value

by Kyle on · Posted in Ruby

To find the index for the maximum value in an array, two array methods are chained together, Enumerable#each_with_index and Enumerable#max.

a = [3,4,5,2]
 
a.each_with_index.max
#=> [5, 2]
 
a.each_with_index.min
#=> [2, 3]

Inserting A String Into A String

by Kyle on · Posted in Ruby

Inserts other_str before the character given at the index, modifying the string. Negative indices count from the end of the string, and insert after the given character. The intent is to insert a string so that it starts at the given index.

"abcd".insert(0, 'X')    #=> "Xabcd"
"abcd".insert(3, 'X')    #=> "abcXd"
"abcd".insert(4, 'X')    #=> "abcdX"
"abcd".insert(-3, 'X')   #=> "abXcd"
"abcd".insert(-1, 'X')   #=> "abcdX"

You could also do this:

"abcd".sub(/^.{2}/,'\0X') #=> abXcd

Accessing Pi In Ruby

by Kyle on · Posted in Ruby

Math::PI
#=> 3.14159265358979

Rounding Up A Float In Ruby

by Kyle on · Posted in Ruby

0.3.ceil
#=> 1
 
2.1.ceil
#=> 3