Passing multiple multi-line strings as arguments to a ruby method


Ever had a need to pass not just one, but two or even multiple multiline strings to a method in one go?

Here is how I did it before:

    # I have a function that will take strings as arguments
    # and set their cases accordingly.
    def print_my_strings(string_a, string_b)
      puts string_a.upcase
      puts string_b.downcase
    end

    # First, assign the strings to variables using the multiline string notation.
    string_a = <<STRA
    Hello, I am string A,
    and I am wasting lines of code.
    STRA

    string_b = <<STRB
    Hello, I am string B,
    and I am ALSO wasting lines of code.
    STRB

    # and call it
    print_my_strings(string_a, string_b)

This is perhaps a little inefficient if you know you won't be needing those variable assignments later on.

Why not get rid of them?

Here is a better way.

  print_my_strings(< <STRA, <<STRB)
  Hello, I am string A
  and I am not wasting any lines
  STRA
  And I am string B,
  also not wasting precious any lines of code either.
  STRB

  # will output
  HELLO, I AM STRING A
  AND I AM NOT WASTING ANY LINES
  and i am string b,
  also not wasting precious any lines of code either.

For fore on multiline strings, checkout Jay Fields' Thoughts.