पाठ 3 / 25

Variables, nil, Strings and Symbols

Use variables, truthiness, strings, symbols and numbers correctly.

The basics, the Ruby way

Ruby variables need no declarations: count = 0. Naming conveys scope: local_variable, @instance_variable, @@class_variable (rarely used), $global (avoid) and CONSTANT. nil represents "no value", and in conditions only nil and false are falsy; everything else, including 0, "" and [], is truthy, which surprises developers coming from JavaScript or Python. Strings are mutable sequences of characters with interpolation in double quotes ("Total: #{total}"); single quotes are literal. Many projects add the magic comment # frozen_string_literal: true so string literals are immutable, and Ruby 3.4 can emit deprecation warnings when unannotated literals are mutated, preparing for frozen literals by default. Symbols (:paid, :city) are immutable, interned identifiers, ideal for hash keys and names, while strings are for text data. Numbers include arbitrary-precision Integer, Float and BigDecimal (from the bigdecimal gem) for money; integer division truncates (7 / 2 is 3), so use 7.fdiv(2) or 7 / 2.0 when you need decimals.

Truthiness, symbols and numbers

Only nil and false are falsy; 0 and empty strings are truthy.

# frozen_string_literal: true

stock = 0
puts "0 is truthy in Ruby" if stock          # prints
puts "empty string is truthy" if ""         # prints

city = nil
puts city.nil?                                # true
label = city || "Unknown"                     # default when nil or false

status = :paid                                # symbol: an identifier
puts status == :paid                          # true
puts "paid".to_sym == :paid                   # true

puts 7 / 2                                    # 3 (integer division)
puts 7.fdiv(2)                                # 3.5
puts 2**100                                   # big integers just work

require "bigdecimal"
exact = BigDecimal("0.1") + BigDecimal("0.2")
puts exact.to_s("F")                         # 0.3 exactly

greeting = "Hello"
# greeting << " world"                        # FrozenError with frozen_string_literal
new_greeting = "#{greeting} world"            # build a new string instead

Only nil and false are falsy

A check like if count is true even when count is 0. Write if count.positive? or unless count.zero? to express what you mean.

त्वरित जाँच: Which values are falsy in Ruby?

  • 0, "", nil and false
  • Only false
  • Only nil and false
  • nil, false and empty arrays
Answer

Only nil and false — Ruby treats every value except nil and false as true in conditions.