hoodwink.d enhanced
RSS
2.0
XHTML
1.0

RedHanded

Simpler Ways #

by why in bits

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 []=.

said on 15 Jul 2005 at 13:28

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| ... }

said on 15 Jul 2005 at 15:19

Ooh, that’s very nice, especially the Array#* method, that should simplify many of my Rails programs.

said on 15 Jul 2005 at 15:57

This:

records.map { |r| r.to_s }.join "\n"

can be shorter, I think. Array#join does to_s automatically. If records provides a to_a method, you could write

records.to_a.join "\n"

without writing a new method.

said on 15 Jul 2005 at 16:25

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:

If called with an array argument, writes each element on a new line.

irb(main):004:0> puts %w(an array of words)
an
array
of
words
said on 15 Jul 2005 at 16:39

@1&2 : Holy kanoodle bunnies! That’s jawsum! I have got to read the Pickaxe section on the built-in stuff.

said on 16 Jul 2005 at 02:23

there is always a more elegant way in Ruby.

said on 16 Jul 2005 at 04:31

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).

said on 16 Jul 2005 at 04:45

Oh my fault – Ruby already has these features?

She’s always good for another surprise. More of that!

Comments are closed for this entry.