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!

28 comments:

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


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

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

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

    ReplyDelete
  3. Finally a simple to understand information, appreciated!

    Also visit my blog:

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

    ReplyDelete
  4. 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

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

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

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

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

    ReplyDelete
  9. 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

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

    ReplyDelete
  11. 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

    ReplyDelete
  12. "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

    ReplyDelete
  13. As the Head of SEO, I specialize in providing SEO services that enhance online visibility and drive organic growth. With a deep understanding of search algorithms and user behavior, I empower businesses to achieve their digital marketing goals. My passion lies in staying ahead of industry trends and delivering measurable results. Visit our services to learn more.

    ReplyDelete
  14. If you're considering pursuing vision correction, Restivo Eye offers a range of options tailored to meet individual needs. Located in the vibrant city of Austin, the clinic specializes in LASIK surgery, a popular procedure known for its effectiveness in treating refractive vision problems such as myopia, hyperopia, and astigmatism.

    The experienced team of professionals is dedicated to providing the highest quality of care, ensuring that each patient receives a thorough evaluation and personalized treatment plan. With advanced technology and a commitment to patient education, Eye LASIK Austin strives to help achieve clearer vision and enhance your overall quality of life.

    ReplyDelete
  15. Ruby Shorthand is a condensed style of writing Ruby code that makes use of the language's strong capabilities and flexible syntax to make it more effective and readable. It frequently uses syntactic sugar, blocks, and procedures to cut down on verbosity without compromising clarity. indecency with child sexual contact For instance, Ruby provides shortcuts such as the map or select methods to iterate across collections more compactly than writing a whole each loop.

    ReplyDelete
  16. It is a unique system of rapid writing designed to help individuals record information quickly and efficiently. Developed with simplicity in mind, this shorthand method relies on a series of symbols, abbreviations, and streamlined letter formations to represent common words and phrases. cps lawyer near me

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. This comment has been removed by the author.

    ReplyDelete
  20. A Technology Blog is an online platform focused on the latest developments in technology. It covers topics like gadgets, software, apps, AI, and emerging tech trends. The blog provides reviews, tutorials, and analysis for tech enthusiasts and professionals. It often features news updates, expert opinions, and product comparisons. Overall, a technology blog aims to inform, educate, and engage readers about the digital world.
    JeetWin
    9Wickets

    ReplyDelete
  21. Ruby Shorthand presents a concise and practical approach that makes working with Ruby more efficient and enjoyable. The content focuses on simplifying common tasks, highlighting smart shortcuts, and encouraging cleaner, more readable code without sacrificing clarity. Whether for beginners looking to speed up their learning or experienced developers aiming to refine their workflow, Ruby Shorthand serves as a helpful, time-saving resource that reinforces best practices in an accessible way.
    Roofing company Selangor

    ReplyDelete
  22. This was a great post. what you said is really helpful to me and it was really interesting as well. Keep up with your good work
    MCW77 Casino Games

    ReplyDelete

  23. I found this post very interesting and informative. Thanks!
    Law Offices Of SRIS, P.C

    ReplyDelete
  24. Really enjoyed this article. Looking forward to your next post! warranty lawyer fairfax county

    ReplyDelete
  25. Convenient housing option for visitors, providing privacy, flexibility, and comfortable living during temporary stays gatlinburg property management

    ReplyDelete