Ruby's named parameters with hyphens

786 views Asked by At

I often have to generate SVG files, and I like doing so with Ruby's Nokogiri. The nice thing about Nokogiri is that it lets you create attributes passing a hash to their "functions", like so

doc.rect(:x => 0, :y => 0, :width => 100, :height => 100)

which is great. There are some attributes that have hyphens: in that case you can just take advantage of Ruby's awesomeness and do something like

doc.rect(:x => 0, :y => 0, :width => 100, :height => 100, :stroke => 'black', 'stroke-width' => 3)

and all is relatively well. Enter Ruby 2.0 and named parameters. I much prefer this syntax, it's a bit more concise and a bit more smalltalkesque, which I like. However, the only way to create hyphenated attributes now is to mix the two approaches, provided that you place the 'hash' after the named parameters (I assume it has to be this way, but I haven't checked). In any case, it's ugly.

Is there any way you wise people can conjure up to create hyphenated attributes using the named parameters syntax?

EDIT: To clarify, named parameters look like this:

doc.rect(x: 0, y: 0, width: 100, height: 100)
2

There are 2 answers

5
Aleksei Matiushkin On

Use either

'stroke-width'.to_sym

or

:'stroke-width'

Both evaluate to symbol. Actually, since the named parameters simply derived syntax from new ruby2 hash notation, you still may mix both like:

params = { named: 'Param1', :'old-style' => 'Param2' } 

and, hence:

doc.rect x: 0, y: 0, :'stroke-width' => 3

It’s the syntax sugar only, inside it is a well-known old good hash. BTW, there is no way to omit hash-rockets for keys, containing \Ws.

0
Jörg W Mittag On

This is not possible. Hyphens are not legal in an identifier.

Think about it: how would you know whether a-b means the identifier a-b or a minus b?