Showing posts with label note. Show all posts
Showing posts with label note. Show all posts

Monday, September 22, 2008

Dynamic programming advantage

Want to show you some pieces of Ruby code that do the same thing.

Original version:
FIELDS = [ 'first', 'last',      'band' ]
DATA = [['Kurt', 'Cobain', 'Nirvana'],
['Jimi', 'Page', 'Led Zeppelin'],
['Noel', 'Gallagher', 'Oasis'],
['Thom', 'Yorke', 'Radiohead']]

def combine_fields_and_data(fields, data)
new_data = []
data.each do |row|
row_hash = {}
row.each_with_index do |column, i|
row_hash[fields[i].to_sym] = column
end
new_data.push(row_hash)
end
return new_data
end

Small_logo

And Adam's refactoring

def combine_fields_and_data(fields, data)
data.map { |row| Hash[*fields.zip(row).flatten] }
end

Adam code utilize Ruby built-in Array and Hash utilities that make his code extremely short.

Read more about Array utilities here.

Saturday, September 20, 2008

Ruby x.kind_of?


module M; end

class A; end

class B < A
include M
end

b = B.new

b.kind_of? A # => true
b.kind_of? B # => true
b.kind_of? M # => true

b.class == A # => true
b.class == B # => false
b.class == M # => false

A === b # => true
B === b # => true
M === b # => true



Reference:
http://refactormycode.com/codes/487-x-kind_of-myclass-or-x-class-myclass

Saturday, September 13, 2008

Ruby Paramater's Default Value


def foobar(a, b='b', c)
...
end

foobar(1, 2, 3)
# a => 1
# b => 2
# c => 3

foobar(1, 2)
# a => 1
# b => 'b'
# c => 2


define bar(a, b='b', c='c', d)

bar(1, 2, 3)
# a => 1
# b => 2
# c => 'c'
# d => 3


---
Prefer using default value for parameter from right to left direction

References:

Friday, September 12, 2008

Ruby Equality


a = "a string"

a === "a string" # => true
a === String # => false

String === "xyz" # => true
"xyz".kind_of? String # => true

(1..5) === 3 # => true
(1..5).include? 3 # => true

/\d/ === "123" # => true

# === is used in "case" statement

b = a
a.equal? b # Returns true if the object_id’s are equal.

1 == 1.0 # => true (do type conversion)
1.==(1.0) # underlying of ==
1.eql? 1.0 # => false (don't do type conversion)



References: