Quantcast

Ruby on Rails, Io, Lisp, JavaScript, Dynamic Languages, Prototype-based programming and more...

Technoblog reader special: $10 off web hosting by FatCow!

Wednesday, November 08, 2006

Functional Programming in Ruby

In Ruby, iteration is done mainly functionally with methods like each and map. We call this type of iteration functional because we are passing a function to be called on each item in the collection.

[1,2,3].each { |item| puts item + 1 }

In this example. the function being passed is { |item| puts item + 1 }. In fact!

print_function = lambda { |item| puts item + 1 }
[1,2,3].each &print_function

Accomplishes the exact same behavior.

This is very much from the functional programing paradigm. Now, one thing that I can not stand to see in Ruby code is this.

def convert(old)
new = Array.new
old.each do |item|
new << transform(item)
end
new
end

The first hint that there is something wrong is the very odd call to return the new variable at the end of the convert method. It seems odd and awkward, and that is a hint that you are working against the grain. Here is how it should look.

def convert(old)
old.map { |item| transform(item) }
end

Or alternatively:

def convert(old)
old.map &method(:transform)
end

Notice how clean and beautiful this is. We are working with the grain of functional programming here. Not only that, but there is less to debug, less to maintain and it takes less time to grok what is going on.

If you want to learn more about the functional programming roots of Ruby, I recommend learning OCaml, I am really enjoying it.

You should follow me on twitter here.

Technoblog reader special: click here to get $10 off web hosting by FatCow!

20 Comments:

Anonymous j`ey said...

Although, some of this only works with Symbol#to_proc of course!

11:57 PM, November 08, 2006

 
Anonymous zerohalo said...

Thanks, Lucas - though I've read and coded this sort of thing before, having some of these things spelled out from different perspectives is nice for those of us learning Ruby.

I understand passing a proc to old.map, but I don't get how &method(:transform) works. I'm assuming 'transform' is a custom method defined in the class. Does that mean that &method will call the 'transform' method, automatically passing each element in 'old' to it and returning the value? Is there any advantage of using that over { |item| transform(item) } ?

11:58 AM, November 09, 2006

 
Anonymous Anonymous said...

A real functional language is even better:

convert = map transform

(Haskell)

12:28 PM, November 10, 2006

 
Anonymous Anonymous said...


A real functional language is even better:

convert = map transform

(Haskell)

Damn straight!

2:56 PM, November 10, 2006

 
Anonymous Anonymous said...

As an aside, what OCaml book(s) do you recommend? I almost bought the Practical Ocaml book that just came out, but I'm seeing lots of bad reviews of that book.

Also, how about a PDX OCaml meetup?

3:19 PM, November 10, 2006

 
Anonymous Olle Jonsson said...

Thanks, Lucas, I found some neat stuff in libxml-ruby connected to this while implementing your more idiomatic way of expression in some code I had inherited.

Here is the blog post about it.

8:08 AM, November 12, 2006

 
Anonymous Curt Sampson said...

I don't recommend Practical OCaml; I have it and it's certainly not a good book for learning a functional programming style. I've got a longer review up on lambda-the-ultimate.org, in the item on that book.

In fact, the book put me off OCaml so much that I've switched to developing in Haskell instead. Haskell syntax is much more elegant.

However, if you're new to functional programming, a very good book to start with is The Little Schemer. It will really give you the feel of FP.

8:11 PM, November 30, 2006

 
Anonymous Curt Sampson said...

I don't recommend Practical OCaml; I have it and it's certainly not a good book for learning a functional programming style. I've got a longer review up on lambda-the-ultimate.org, in the item on that book.

In fact, the book put me off OCaml so much that I've switched to developing in Haskell instead. Haskell syntax is much more elegant.

However, if you're new to functional programming, a very good book to start with is The Little Schemer. It will really give you the feel of FP.

8:12 PM, November 30, 2006

 
Anonymous Anonymous said...

i buy hydrocodone at buy hydrocodone - can't find any cheaper

7:02 AM, January 28, 2007

 
Blogger CarlH said...

Why don't you use collect!?

8:58 AM, April 03, 2007

 
Blogger Kerry Buckley said...

CarlH said...
Why don't you use collect!?

collect and map are synonyms, and can be used interchangably.

5:01 AM, July 03, 2007

 
Anonymous Anonymous said...

i downloaded ruby, and i want to learn to program and everyone says its the easiest language to learn and ive read alot of tutorials on how to program for beginners but i still have literally no idea where to start... will someone please help me understand

4:36 PM, December 26, 2007

 
Anonymous Andras said...

Hello!
My pick for the easiest language to learn would be definitely Python. I recommend you start with that. It is simple and clean, yet powerful. Ruby is really nice but Python is way more straightforward for a beginner, and is well documented.

3:00 AM, January 17, 2008

 
Blogger Geira said...

Instead of Practical OCaml, check out The Functional Approach to Programming by Cousineau and Mauny. Admittedly it uses Caml Light instead of OCaml, but the differences are very small (except that it doesn't cover OOP). It's gotten good revies and covers nicely the main points of FP.

There's also OCaml for Scientist by Harrop which I haven't read, plus a French O'Reilly book that's been translated into English.

12:37 PM, June 05, 2008

 
Blogger lina123 Chen said...

chenlina20150626
chenlina20150626
coach outlet store online
cheap oakley sunglasses
burberry sale
coach outlet
abercrombie fitch
ray ban uk
michael kors outlet online
kids lebron shoes
lv outlet
true religion sale
louis vuitton outlet
cheap ran bans
tory burch outlet
abercrombie and fitch
hollister clothing
ghd straighteners
prada
air max 90
fendi handbags
michael kors outlet
jordan 11 columbia
louis vuitton outlet
louis vuitton outlet
cheap jerseys
gucci belt
coach factory outlet
louis vuitton outlet
ralph lauren uk
hermes birkin
michael kors outlet online
true religion sale
p90x
louis vuitton
tod's outlet
kobe bryant shoes
pandora bracelets
michael kors outlet
michael kors outlet online
jordan 4 toro
michael kors

6:19 PM, June 25, 2015

 
Blogger Nesma Ali said...


شركة عزل خزانات بالدرعية
شركة عزل خزانات بعنيزة
شركة عزل خزانات ببريدة
شركة عزل خزانات بالمذنب
شركة عزل خزانات بعفيف
شركة عزل خزانات بالغاط
شركة عزل خزانات بثادق
شركة عزل خزانات بالدوادمى
شركة عزل خزانات بالمزاحمية
شركة عزل خزانات بالقويعية
شركة عزل خزانات بوادي الدواسر
شركة عزل خزانات بالدلم
شركة عزل خزانات برماح
شركة عزل خزانات بالأفلاج
شركة عزل خزانات بحريملاء
شركة عزل خزانات بالزلفي
شركة عزل خزانات بضرما
شركة عزل خزانات بشقراء
شركة عزل خزانات بالسليل
شركة عزل خزانات بالقصيم
 شركة عزل خزانات بحوطة بني تميم
شركة عزل خزانات بالحريق
 شركة عزل خزانات بالمجمعة
شركة عزل خزانات بمرات
شركة عزل خزانات بالرس
شركة عزل خزانات شرق الرياض
شركة عزل خزانات غرب الرياض
شركة عزل خزانات شمال الرياض
شركة عزل خزانات جنوب الرياض
شركة عزل خزانات وسط الرياض

1:37 AM, September 02, 2015

 
Blogger Da Shuai Guo said...

19guowenhao0914
oakley sunglasses, http://www.oakleysunglassescanada.com/
ray ban sunglasses outlet, http://www.raybansunglass.us.com/
cheap jordans, http://www.cheapjordanshoes.in.net/
coach outlet online, http://www.coachoutletstores.com.co/
mbt shoes outlet, http://www.mbtshoesoutlet.us.com/
michael kors factory outlet, http://www.michaelkorsfactoryoutlet.us.org/
coach outlet store, http://www.coachoutletonline-store.us.com/
asics, http://www.asicsisrael.com/
nike roshe run, http://www.rosherunshoessale.com/
iphone 6 cases, http://www.iphonecase.name/
ralph lauren uk, http://www.ralphlaurenoutletuk.org.uk/
real madrid jersey, http://www.realmadridjerseystore.com/
bears jerseys, http://www.chicagobearsjerseys.us/
ralph lauren outlet, http://www.ralphlaurenoutletuk.org.uk/
christian louboutin outlet, http://www.christianlouboutinoutlet.name/
polo ralph lauren, http://www.poloralphlauren.us.org/
louis vuitton outlet store, http://www.louisvuittonoutlet.in.net/
tory burch outlet, http://www.toryburch.in.net/
dolphins jerseys, http://www.miamidolphinsjersey.com/
replica handbags,replica handbags outlet,cheap handbags,purses and handbags,wholesale replica handbags,replica bags,bags outlet,replica handbags wholesale,cheap purses,discount handbags,handbags sale,wholesale purses,handbags and purses,replica purses
basketball shoes, http://www.basketballshoes.us.com/
coach outlet, http://www.coach-outlet-store.us.com/
true religion jeans, http://www.truereligionoutletstore.us.com/
ralph lauren outlet, http://www.ralphlaurenoutlet.in.net/
herve leger, http://www.herveleger.us.com/

1:07 AM, September 15, 2015

 
Blogger Minko Chen said...

michael kors outlet
barbour jackets
tiffany and co
ed hardy clothing
miami dolphins
toms outlet store
coach handbags outlet
true religion outlet
nfl jerseys
snapbacks wholesale
true religion outlet
pittsburgh steelers
oakley sunglasses wholesale
cyber monday deals
mac cosmetics
canada goose outelt
canada goose jackets
abercrombie and fitch
michael kors outlet
michael kors factory online
1114minko

9:05 PM, November 13, 2015

 
Blogger Hoàng Anh said...

Write more, thats all I have to say Chung cư Vinhomes Liễu Giai Giá Gốc - Dự án Vinhomes Liễu Giai - Chung cư Vinhomes Liễu Giai - Vinhomes Central Palace Liễu Giai - Literally, it seems as though you relied on the video to make your point.

8:23 PM, December 18, 2015

 
Blogger hary said...

オニツカタイガー
オニツカタイガーメキシコ66
オニツカタイガーセラーノ
メキシコミッドランナー
オニツカタイガー メキシコミッドランナー
ASICS GEL LYTE Vティンバーランド 白
ティンバーランドスニーカー
ティンバーランドレディースコーディネート
ティンバーランドレディーススニーカー
ティンバーランドレディース ブーツ
ティンバーランドレディース靴
アンダーアーマーバッシュ
NIKE SB
NIKE STEFAN JANOSKI MAX
ステファン ジャノスキー マックス NIKE STEFAN JANOSKI MAX
ステファン ジャノスキー マックス
ナイキ エアハラチ レディース
ナイキ エアハラチ 通販
ナイキ エアハラチ コーデ
ナイキ エアハラチ ラン
ナイキ エアハラチ ライト
ナイキ エアハラチ メンズサッカースパイクナイキマジスタ
マジスタオーパス
マジスタオーパスfg
マジスタ オブラ
マジスタオーデン
ナイキ マジスタ
ナイキサッカースパイクマジスタ
サッカースパイク マジスタ
マジスタ FGニューバランス 574 ネイビー
ニューバランス574 レディース
ニューバランス 576uk
ニューバランス 576 ネイビー
ニューバランス m996 ネイビー
ニューバランス 996 通販
ニューバランス m996 gy
ニューバランス m996
ニューバランス 996 グレー
ニューバランス 996レディース
new balance 996

11:32 PM, January 08, 2016

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home

 

If you like this blog, you might also like top photography schools.