← Ruby EnglishChapter 02 of 13

Variables, Types, and Constants

## Learning Objectives - Declare and use variables - Understand Ruby's data types - Work with constants - Master type conversion ## Variables ### Declaration and Assignment ```ruby age = 25 # Integer name = "Ruby" # String price = 19.99 # Float is_active = true # Boolean nothing = nil # Nil (null) # Multiple assignment x, y, z = 1, 2, 3 ``` ### Variable Naming Rules - Start with lowercase letter or underscore - Can contain letters, numbers, and underscores - Case-sensitive - Cannot use reserved words ```ruby first_name = "John" # Valid _count = 0 # Valid myVar = "test" # Valid (but not convention) 2nd_place = "silver" # Invalid class = "ruby" # Invalid (reserved word) ``` ## Data Types ### Integer ```ruby age = 25 negative = -10 hex = 0xFF # 255 in hexadecimal octal = 0755 # 493 in octal binary = 0b1010 # 10 in binary # Underscores for readability population = 7_000_000_000 ``` ### Float ```ruby price = 19.99 temperature = -5.5 scientific = 1.5e-3 # 0.0015 ``` ### String ```ruby single = 'Hello' # Single quotes - literal double = "Hello" # Double quotes - allows interpolation interpolated = "Value: #{2 + 2}" # "Value: 4" # Multi-line string poem = <<~TEXT Roses are red, Violets are blue, Ruby is awesome, And so are you. TEXT ``` ### Boolean ```ruby is_valid = true is_empty = false # Truthiness # falsy values: false, nil # truthy values: everything else (0, "", [], etc.) ``` ### Nil ```ruby empty = nil # Check for nil if empty.nil? puts "Value is nil" end # Safe navigation name = nil puts name&.upcase # nil instead of error ``` ## Constants ```ruby MAX_SIZE = 100 PI = 3.14159 # Constants can be modified but Ruby warns MAX_SIZE = 200 # Warning: already initialized constant ``` ## Symbols Symbols are immutable, reusable identifiers: ```ruby # Symbol creation :pending :symbol_name :"complex symbol" # vs String "pending" # Creates new object each time :pending # Same object, reused # Common use: hash keys user = { name: "Alice", age: 30 } # This is equivalent to: user = { :name => "Alice", :age => 30 } ``` ## Type Conversion ### To String ```ruby age = 25 puts age.to_s # "25" puts age.to_s.class # String # Integer to string [1, 2, 3].join # "123" ``` ### To Integer ```ruby "42".to_i # 42 "42.9".to_i # 42 (truncates) "hello".to_i # 0 (non-numeric becomes 0) "42".to_i(16) # 66 (hex to decimal) ``` ### To Float ```ruby "3.14".to_f # 3.14 "42".to_f # 42.0 ``` ### To Array ```ruby "hello".chars # ["h", "e", "l", "l", "o"] "one,two,three".split(",") # ["one", "two", "three"] ``` ### To Symbol ```ruby "pending".to_sym # :pending :pending.to_s # "pending" ``` ## Checking Types ```ruby value = 42 value.is_a?(Integer) # true value.is_a?(String) # false value.instance_of?(Integer) # true # Type checking if value.respond_to?(:to_s) puts value.to_s end ``` ## Parallel Assignment ```ruby # Swap variables a, b = 1, 2 a, b = b, a puts "#{a}, #{b}" # "2, 1" # Rest operator first, *rest = [1, 2, 3, 4, 5] puts first # 1 puts rest # [2, 3, 4, 5] ``` ## Variable Scope ```ruby # Local variable - within method/block def example local = "I am local" puts local end # Instance variable - across methods in a class class User def initialize(name) @name = name # Instance variable end def greet "Hello, #@name" end end # Class variable - shared across class hierarchy class Counter @@count = 0 def initialize @@count += 1 end def self.total @@count end end ``` ## Summary - Variables: no type declaration needed, inferred from assignment - Integers: Fixnum (legacy) and Bignum unified as Integer - Strings: Double quotes allow interpolation, single quotes are literal - Symbols: Immutable identifiers, more efficient than strings - Constants: UPPERCASE, Ruby warns on reassignment - Type conversion: `to_s`, `to_i`, `to_f`, `to_a`, `to_sym` - Truthy: everything except `false` and `nil`

Comments

Comments powered by Giscus

To enable comments, add your Giscus embed code here.

Learn more about Giscus →