Sunday, November 25, 2007

Ruby Shorthand

Justin.tv's web code is written in Ruby. I've found myself using the same collection idioms over and over, so I've abstracted several of them into a file called shorthand.rb.



Most of our web code consists of manipulating collections in one form or another, which is probably why all the shorthand methods are for that. I'm particular proud of my % operator, which I believe is a specialized mapcar in spirit. Without further ado, code!




module Enumerable
def %(field)
map {|o| o.send(field)}
end
end

class Hash
def keys_sorted_by_value(options = Hash.new, &block)
limit = options[:limit] || size
offset = options[:offset] || 0

sorted = map.sort_by do |key, value|
if block
yield(key, value)
else
value
end
end

sorted.reverse! if options[:reverse]

sorted.map {|key, value| key}.slice(offset, limit) || Array.new
end

def hmap
h = dup
keys.each do |k|
h[k] = yield h[k]
end
h
end

def to_params
map {|k, v| "#{k}=#{CGI::escape v.to_s}"}.join("&")
end
end


class Array
def hash_by(field)
h = Hash.new
each {|o| h[o.send(field)] = o}
h
end

def center_first
centered = Array.new
last_pushed = false
each do |x|
centered.push(x) unless last_pushed
centered.unshift(x) if last_pushed
last_pushed = !last_pushed
end
centered
end

def random_subset(n=size)
shuffle.slice(0, n)
end

def shuffle
sort_by { rand }
end

def divide
evens = Array.new
odds = Array.new
each_with_index do |x, i|
if i % 2 == 0
evens << x
else
odds << x
end
end
[evens, odds]
end

def remove!(item)
reject! {|x| x == item}
end

def remove(item)
reject {|x| x == item}
end
end


Other coders: If you have your own idioms like these, I'd love to see them! Post them!

15 comments:

토토 said...

Excellent article. I certainly appreciate this website.
Stick with it!


토토사이트
스포츠토토티비
토토

토토 said...

Everyone loves it when people come together
and share opinions. Great site, continue the good work!

토토
배트맨토토
배트맨토토프로

Majortotositepro1 said...

Finally a simple to understand information, appreciated!

Also visit my blog:

토토사이트
경마사이트
바카라
토토사이트

Majortotositepro1 said...

It’s nearly impossible to find well-informed people in this particular topic,
but you sound like you know what you’re talking about!

majortotositepro1
oncasinositenet1
totopickpro1
majortotositepro1

sportstototopcom said...

This is a wonderful article, I really appreciate your efforts and I will be waiting for your next post thank you once again. 스포츠토토

gostopsite 고스톱사이트 said...

Your choice of writing is really amazing.
카지노사이트

casinositewiki 카지노사이트 said...

I am really impressed with this blog article, Keep it up!
카지노사이트위키
온라인카지노사이트
카지노사이트탑
바카라사이트

sportstotolink said...

When I read your article on this topic, the first thought seems profound and difficult.
토토
먹튀검증

casinositezone said...

Your post is very interesting to me. Reading was so much fun.
카지노사이트
바카라사이트

safecasinositenet said...

I think the reason reading is fun is because it is a post related to that I am interested in.
바카라사이트
온라인카지노

casinositenetcom said...

It’s very straightforward to find out any topic on net as compared to books, as I found this article at this site
온라인카지노
카지노

johnstepan said...

This is a very good tips especially to those new to blogosphere, brief and accurate information… Thanks for sharing this one. A must read article.
Divorce Attorneys Fairfax VA

raelynn said...

thanks for sharing this article , really i got a lot of useful information in your blog post Divorcio de Corte Suprema de Nueva York

Anonymous said...

A protective order in Virginia is a legal measure designed to safeguard individuals from domestic violence, harassment, or threats. Violating such an order can result in serious legal consequences, including fines and imprisonment. Obtaining a protective order is a critical step for those seeking protection from potential harm in Virginia. motion to dissolve protective order virginia

villa rao said...

"Ruby Shorthand" is a highly informative and practical guide that introduces readers to a streamlined and efficient method of using the Ruby programming language. The book is designed for both novice and experienced programmers, offering clear explanations and step-by-step instructions to master shorthand techniques that enhance coding speed and readability. Each chapter is packed with useful tips, code snippets, and real-world examples that demonstrate how to simplify complex coding tasks.
Abogado de DUI Culpeper VA