Simpler Ways #
1. Less explicit to_s.
Like in joining arrays: records.map { |r| r.to_s }.join "\n"
Agg, get away casting! Could just be: records * "\n"
2. Forgetting grep works with classes.
I’ll be searching for a class: animals.find_all { |a| a.is_a? Hawk }
Rather: animals.grep Hawk
3. Structs for simple classes.
Object still needs an attrs
method. Struct has members
.
Object uses instance_variable_set
. Struct uses []=
.
Robo Suckage
4. use to_a for “one or many”-style arguments. to_a applied to an array returns the same array.
x = 23 y = [3,4,32]
x.to_a = [23] y.to_a = [3,4,32]
So, without knowing whether x is an array or a single object:
x.to_a.each {|thing| ... }
Vincent Foley
Ooh, that’s very nice, especially the Array#* method, that should simplify many of my Rails programs.
murphy
This:
can be shorter, I think. Array#join does to_s automatically. If records provides a to_a method, you could write
without writing a new method.
Ken Kunz
Didn’t know about
Array#*
... interesting. The string-argument-specific behavior almost feels a little too perl-ish. Not sure yet if I like it.Another one to remember is
IO#puts
with an array:yerejm
@1&2 : Holy kanoodle bunnies! That’s jawsum! I have got to read the Pickaxe section on the built-in stuff.
i_love_nitro
there is always a more elegant way in Ruby.
chris2
Robo: Note that Object#to_a is deprecated, and String#to_a can be “suprising”... the recommended way is [*foo] for now (despite the String issues).
murphy
Oh my fault – Ruby already has these features?
She’s always good for another surprise. More of that!
Comments are closed for this entry.