Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

NY Standup 6/7/2011: Making the cut.

Interesting Things

  • min_by / max_by: Ian points us towards Enumerable‘s handy #min_by and #max_by. Want to get the string in a collection whose second-to-last character is earliest in the alphabet?

    ["ayx", "zbaaaz"].min_by { |s| s[-2] }  # => "zbaaaz"
  • keep_if: On the subject of collections, Kris points out Ruby 1.9’s Array#keep_if (note the missing bang at the end), which mutates the array to remove things for which the block returns false. For example,

    a = ["ayx", "zbaaaz"]
    a.keep_if { |s| s.length < 4 }
    a                                       # => ["ayx"]

    Another method, Array#select! behaves very similarly. The only difference is that when it doesn’t change the array, #select! returns nil while #keep_if returns the array. Returning nil matches the behavior of other mutators like String#sub!, while #keep_if breaks the pattern. Thus,

    ["ayx", "zbaaaz"].keep_if { |s| s.length < 4 }    # => ["ayx"]
    ["ayx", "zbaaaz"].select! { |s| s.length < 4 }    # => ["ayx"]
    ["ayx", "zbaaaz"].keep_if { |s| s.length < 10 }   # => ["ayx", "zbaaaz"]
    ["ayx", "zbaaaz"].select! { |s| s.length < 10 }   # => nil

    It is, perhaps, of questionable value.

  • $("textarea").clone(): Ian discovered that when jQuery clones form fields, the clones of input elements retain the values of the originals, while textareas and selects become blank.

  • jsFiddle: Sam J. points us towards jsFiddle, a nifty tool for sharing JavaScript snippets. It provides a pane each for JS, CSS, and HTML, and then a pane that shows the results. Then you can share it like a Gist or a Pastie.

  1. grosser says:

    keep_if: an alias that behaves slightly different, feels like good old php times :D

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *