c = [something]
if c :foo then
puts “blah”
end
SyntaxError: compile error
(irb):3: parse error, unexpected kTHEN, expecting kEND
from (irb):5
from :0
What would you expect an expression of the form ‘c :symbol’ to mean
in the first place? The only parallel I can think of is some sort of
implicit concatenation like happens with strings (“foo” “bar” =>
“foobar”), but I don’t think that’s a generalisable operation.
or ‘(’
when bar :baz then “bur”
^
Is this intentional? Having the expression span multiple lines
doesn’t solve it.
At this point it strikes me as intentional in the sense that it’s not
a valid expression to begin with. Sorry if that’s not the most
helpful answer; maybe further explanations might clear things up for me.
I guess when binds more tightly than a parentheses-less method call.
You could do:
when bar(:baz) …
Thank you for the response. Yes, it seems there is no way to get around
using parentheses. It’s actually just an aesthetic problem; the method
in question has a question mark suffix, and I like to call such methods
without parentheses. Specifically, it was an attempt at an aesthetically
pleasing version of the code in “Symbols are your friend”:
case “foo”
when of_type? :int then “integer”
when of_type? :str then “string”
end
Unfortunately, I’ll have to write it like this:
case “foo”
when of_type?(:int) then “integer”
when of_type?(:str) then “string”
end
It doesn’t really matter that much though – I’m not even sure I like
that solution.
when of_type? :str then “string”
that solution.
:int => Integer,
when :str.like? then ‘string’
[Integer, String, Array].detect{|c| c === ‘foo’ and c.name.downcase}
That would work, but I don’t think classes and types are always the
same. An ordered hash is still a hash, even if it doesn’t descend from
Hash. This way, all objects that respond to #to_hash is in some way a
hash, and I can trust (to some degree) that the object returned when
calling that method implements the interface of Hash.
ordered hash is still a hash, even if it doesn’t descend from Hash. This
way, all objects that respond to #to_hash is in some way a hash, and I can
trust (to some degree) that the object returned when calling that method
implements the interface of Hash.
indeed. still, the technique is more compact than a case: