Problem with "here" document in hash constructor?

J

john_b_andrews

In the following code example, constructing hash1 works fine,
but constructing hash2 gives me a hash with only one key:

###########################################################
hash1 = {
"key1" => "value1" ,
"key2" => "value2"
}

p hash1
p hash1.keys.length

hash2 = {
"key1" => <<EOF
value1
EOF,
"key2" => <<EOF
value2
EOF
}

p hash2
p hash2.keys.length
########################################################

If I move the comma separating the two key/value pairs
to its own line (so that EOF is recognized properly), I get
a syntax error:

T2.rb:17: syntax error
T2.rb:18: warning: useless use of a literal in void context
T2.rb:18: syntax error
"key2" => <<EOF
^

Is there any way to do this using "here" documents (<<EOF)
and the Hash {} constructor style? I know I can do it by
constructing the hash another way, but...

Thanks,

JA
 
J

James Edward Gray II

In the following code example, constructing hash1 works fine,
but constructing hash2 gives me a hash with only one key:

[snip working example]
hash2 = {
"key1" => <<EOF
value1
EOF,
"key2" => <<EOF
value2
EOF
}

Try changing that too:

hash2 = {
"key1" => <<EOF,
value1
EOF
"key2" => <<EOF
value2
EOF
}

Hope that helps.

James Edward Gray II
 
R

Robert Klemme

Plus a bit of explanation / mnemonic: the "<<EOF" is the expression that's
replaced by the here document. That's why you want the "," directly after
"<<EOF".

Kind regards

robert
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top