Interesting Things
min_by/max_by: Ian points us towardsEnumerable‘s handy#min_byand#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′sArray#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!returnsnilwhile#keep_ifreturns the array. Returningnilmatches the behavior of other mutators likeString#sub!, while#keep_ifbreaks 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 } # => nilIt is, perhaps, of questionable value.
$("textarea").clone(): Ian discovered that when jQuery clones form fields, the clones ofinputelements retain the values of the originals, whiletextareas andselects 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.
keep_if: an alias that behaves slightly different, feels like good old php times :D
June 8, 2011 at 9:30 am