IF me like Ruby does

S

Sven Schwyn

Hi there

When fiddling together CSS classes in html_options of my form helpers, I
sometimes have code looking something like the following:

html_options.merge!:)class => "list_item" + ((options[:class_method])?("
list_item_#{object.send(options[:class_method])}"):('')))

The "('')" is pretty ugly, so I'm wondering if there's a more rubyish
way to write this.

Thanks for your hints, -sven
 
S

Sven Schwyn

Here's a version that's easier to read. Assume you want to concat A and
B with a space in between provided the method add_B? returns true.

'A' + ((add_B?)?(' B'):(''))

The closest alternative I came up with:

['A', (' B' if add_B?)].join

The more generic form, however, will not do the trick:

['A', ('B' if add_B?)].join(' ')

However, this adds a tailing space if add_B? returns false.
 
B

Bira

Here's a version that's easier to read. Assume you want to concat A and
B with a space in between provided the method add_B? returns true.

How about "A#{add_B? ' B' :''}"?

If you use double-quoted strings, you can interpolate Ruby code into
them by using #{}.

Ruby will replace the code between #{} with a string containing the
result of the expression inside.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,276
Messages
2,571,384
Members
48,072
Latest member
FaustoBust

Latest Threads

Top