문제

I am trying to use a custom method with here-doc and want to pass parameter (there is no business case, I am merely trying to learn ruby). Is there a way to pass parameter in this case? This is what I have so far.

Simple method, just works fine.

def meth1
  self.upcase
end

str1 = <<MY.meth1
  i am a small case string
MY

# "I AM A SMALL CASE STRING\n"

Now, I thought let us drop some parameters and tried different variations and irb gives me a blank stare.

#variation 1

def meth2( <<EOF1, <<EOF2 )
  EOF1.upcase + "..." + EOF2.downcase
end

str2 = <<MY.meth2
 some string
EOF1
 ANOTHER STRING
EOF2
MY
도움이 되었습니까?

해결책

My guess is that this is what you are trying to do:

def meth2(str1, str2)
  str1.upcase + "..." + str2.downcase
end

str2 = meth2(<<EOF1, <<EOF2)
 some string
EOF1
 ANOTHER STRING
EOF2

str2 # => " SOME STRING\n... another string\n"

If you don't intent to indent, see here. ← See my play with words here?

다른 팁

try something along the lines of

something = "bananas"

str = <<EOF
  this has some #{something} in!
EOF

Try something like this:

def meth2( item1, item2 )
  item1.upcase + "..." + item2.downcase
end

str2 = meth2 <<EOF1, <<EOF2
 some string
EOF1
 ANOTHER STRING
EOF2

The problem you are having is due to not fully understanding how heredoc-style string literals work. The <<DELIMITER part just is telling the parser to get it's string data from the lines that follow it. If there is more than one <<DELIMITER on a line, then they stack, and are read in in sequence. So, in this case, the code above is exactly equivalent to:

def meth2( item1, item2 )
  item1.upcase + "..." + item2.downcase
end

str2 = meth2 " some string\n", " ANOTHER STRING\n"

Most importantly, there is no way to build a heredoc into a function like you were trying to do there... They can only be used in the same places and manner that other String literals, such as "double quoted" or 'single quoted' literals, can be used.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top