I'm trying to make a 'render' call in an erb file where the key of the hash is dynamically named. For example...
<% object_type_abbr = ["pos", "job_description", "policy", "procedure", "step", "task", "product"] %>
<%= render path.to_s,
model_id: @model.id,
object_type_abbr[i]: orphan,
row_no: row_no,
is_orphan: true
%>
The problem is this syntax is not recognized. I have tried using the #{ruby var name} syntax (suggested here), but of course this doesn't work in HTML.
I've also tried object_type_abbr[i].to_sym, which makes no difference.
I know this has to exist, but can't find it.
One solution is to use the =>
notation for that entry in the hash e.g.
model_id: @model.id
object_type_abbr[i].to_sym => orphan,
....
The standard way to map keys to values in a hash is using the key => value
(rocket) notation.
When you write model_id: @model.id
this is shorthand for :model_id => @model.id
- Ruby provides this shorthand because creating hashes where the keys are symbols is such a common use case. But it isn't valid to use this style of syntax for something like object_type_abbr[i]:
where the thing of the left of the colon isn't the name for a symbol.
When you use the =>
notation the key can be any expression, including one that evaluates to a symbol.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With