Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a heredoc as a hash value

Tags:

ruby

I have a method Embed.toggler that takes a hash argument. With the following code, I'm trying to use a heredoc in the hash.

                Embed.toggler({
                    title: <<-RUBY 
                        #{entry['time']}
                        #{entry['group']['who']
                        #{entry['name']}
                    RUBY
                    content: content
                })

However, I'm getting the following error trace:

syntax error, unexpected ':', expecting tSTRING_DEND
                        content: content
                                ^
can't find string "RUBY" anywhere before EOF
syntax error, unexpected end-of-input, expecting tSTRING_CONTENT or tSTRING_DBEG or tSTRING_DVAR or tSTRING_END
                        title: <<-RUBY 
                                      ^

How I can avoid getting this error?

like image 870
maxple Avatar asked Oct 04 '15 20:10

maxple


1 Answers

Add a comma after your <<-RUBY:

Embed.toggler({
    title: <<-RUBY,
        #{entry['time']}
        #{entry['group']['who']
        #{entry['name']}
    RUBY
    content: content
})

this does work in general. I am not sure why it wasn't working in my code though.

It didn't work because hashes require key/value pair to be separated by a comma, like {title: 'my title', content: 'my content' } and your code just didn't have the comma. It was hard to see that because of the cumbersome HEREDOC syntax.

Do you know if there is a way to perform operations on the string?

You're playing with fire. It's always safer (and usually cleaner) to extract a variable and do post-processing on a variable itself:

title = <<-RUBY
   #{entry['time']}
   #{entry['group']['who']
   #{entry['name']}
RUBY

Embed.toggler(title: title.upcase, content: content)

However, if you feel dangerous today, you can just add operations after opening HEREDOC literal, just as you've added the comma:

Embed.toggler({
    title: <<-RUBY.upcase,
        #{entry['time']}
        #{entry['group']['who']
        #{entry['name']}
    RUBY
    content: content
})

But I discourage you from this because it destroys readability.

like image 191
Alexey Shein Avatar answered Oct 29 '22 05:10

Alexey Shein