IntermediateLesson 8 of 16
Symbols & Strings in Detail – Ruby
Symbols vs. strings, important string methods, heredocs and frozen strings.
A symbol (:name) is an immutable name that exists in memory only once. It is ideal for keys, statuses and options. Every string literal, on the other hand, creates a new object (unless frozen).
puts :name.class, "name".class # Symbol, String
puts :name.object_id == :name.object_id # true
puts "name".object_id == "name".object_id # false (two objects)
puts :name.to_s, "name".to_sym.inspect # name, :name
status = :offen
case status
when :offen then puts "to do"
when :erledigt then puts "done"
endString methods you need all the time:
s = " Ruby is fun "
puts s.strip.upcase # RUBY IS FUN
puts "a,b,c".split(",").inspect # ["a", "b", "c"]
puts %w[x y z].join("-") # x-y-z
puts "Ruby".reverse, "Ruby".length, "Ruby"[1..2], "Ruby" * 2 # ybuR, 4, ub, RubyRuby
puts "Banana".gsub("a", "A"), "Banana".sub("a", "A"), "Banana".count("a") # BAnAnA, BAnana, 3
puts "Ruby".start_with?("Ru"), "Ruby".include?("ub") # true, true
puts "hello world".split.map(&:capitalize).join(" ") # Hello World
puts format("%05.1f | %s | %-6s|", 3.14159, "ok", "li") # 003.1 | ok | li |
puts "Price: %.2f EUR" % 4.5 # Price: 4.50 EUR
puts "Ada".center(11, "*") # ****Ada****Heredocs create multi-line text. With <<~ the common indentation is removed.
text = <<~END
Line 1
indented
Line 3
END
puts textThe magic comment # frozen_string_literal: true (first line of the file) freezes all string literals. This saves memory and prevents accidental changes:
# frozen_string_literal: true
s = "abc"
begin
s << "d"
rescue FrozenError => e
puts "Error: #{e.class}" # FrozenError
end
puts(s + "d") # abcd – + creates a new string
kopie = +"abc" # +"..." returns a mutable copy
kopie << "d"
puts kopieWarningMixing
"name" and :name as hash keys is a source of errors: { name: 1 }["name"] gives nil. Make a decision (usually for symbols) and convert input deliberately with to_sym or symbolize_names: true.