BeginnerLesson 2 of 16
Variables, Types & Strings – Ruby
Local variables, numbers, strings, interpolation and constants.
You create variables simply by assigning – without a keyword and without a type. The name is lowercase (snake_case). .class tells you the type.
name = "Ada" # String
alter = 36 # Integer
groesse = 1.68 # Float
aktiv = true # true / false
nichts = nil # nil = "no value"
puts name.class, alter.class, groesse.class, aktiv.class, nichts.classIn double quotes #{...} is evaluated (interpolation), in single quotes it is not. Calculating and converting:
puts "#{name} is #{alter} years old"
puts 'Simple: #{name}' # no interpolation
puts "Next year: #{alter + 1}"
puts 7 / 2, 7 % 2, 7.0 / 2, 2 ** 10, 7.fdiv(2) # 3, 1, 3.5, 1024, 3.5
puts "42".to_i + 1, "3.5".to_f, 42.to_s + "!" # 43, 3.5, 42!
MWST = 0.19 # constant: starts with an uppercase letterStrings in Ruby are mutable. With << you append, frozen? shows whether a string is frozen.
s = "Hello"
s << " World"
puts s # Hello World
puts s.frozen? # false
puts "Ruby".freeze.frozen? # trueWarning
7 / 2 gives 3: two integers are divided using integer division. Use 7.0 / 2 or 7.fdiv(2) for 3.5. And "5" + 5 is a TypeError – Ruby never silently converts between text and number (strong typing).TipUnderscores make large numbers readable:
1_000_000. With Integer("42") and Float("3.5") you convert strictly: invalid input raises an ArgumentError instead of a silent 0 like with "abc".to_i.