Last active
August 29, 2015 13:55
-
-
Save acook/8695438 to your computer and use it in GitHub Desktop.
All you never wanted to know about Strings in Ruby.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# the simple stuff | |
string = 'uninterpolated string' | |
string = "interpolated\nstring" | |
# if you have all kinds of quotes in your strings, these are available if you must | |
string = %q{uninterpolated string} | |
string = %Q{interpolated\nstring} | |
#heredocs! | |
string = <<END | |
heredoc | |
newlines | |
are | |
preserved | |
END | |
string = <<-END | |
heredoc where terminator can have whitespace in front of it | |
leading whitespace inside the string itself is preserved though (boo, hiss/cool, yay - depending on the situation). | |
END | |
string = <<terminators_can_be_whatever | |
Seriously, like anything. So long as its not in the string. | |
#{'Also they can all interpolate.' if true} | |
terminators_can_be_whatever | |
# use any delimiters! (please don't) | |
string = %{interpolated\nstring} | |
string = %(interpolated\nstring) | |
string = %[interpolated\nstring] | |
string = %"interpolated\nstring" | |
string = %'interpolated\nstring' # haha I bet you thought I'd be uninterpolated | |
# works for all % groups! | |
string = %q"uninterpolated string" # don't ever do this or I will find you and destroy you | |
# more fun with interpolation! | |
tab = "\t" | |
newline = "\n" | |
version_string = "ruby version: #{RUBY_VERSION}" | |
code_string = "put any Ruby code in hash brackets and it'll call .to_s on the result: #{Array.new << 5}" # if to_s returns anything other than a String (even a symbol) - Ruby will will make up its own string | |
@some_instance_variable = 'some value' # this isn't the fun part, see the next line | |
interpolate_dat_var = "some var: #@some_instance_variable" # look ma, no brackets | |
# string merging! | |
mix_and_match = "interpolate\n"'more like interp-o-LATE \namirite\n?' # damn this is ugly | |
# single characters too! | |
string = ?x | |
string = ?\n # takes all the backslash interpolations | |
string = ?\u2620 # skull and crossbones! freakin' utf! | |
# bonus round! arrays of strings | |
array = %w{create uninterpolated array of strings} | |
array = %W{create interpolated\narray of strings} |
smathy
commented
Jan 29, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment