Data Types
Data types represent different types of data such as numbers, booleans, strings, etc. As an object-oriented language, all data types are based on classes.
Numbers
Ruby has different types of numbers such as integers and floating point numbers.
# Integer typecount = 1# Float typerating = 1.5# Both float and integer typesmiles = 127hours = 2.5miles_per_hour = miles / hoursputs "Miles per hour: #{miles_per_hour}"# Output: Miles per hour: 50.8
Booleans
A value of either true
or false
.
temp = 100isHot = temp > 80puts isHot# Output: trueif isHotputs "Better wear shorts today!"elseputs "Better wear long pants today!"end# Output: Better wear shorts today!
Strings
A string is a sequence of characters that represents a word or a sentence. They are created by surrounding a sequence of characters with single or double quotes.
puts "Hello World!"puts 'Hello World!'
Arrays
Arrays store data in a list. An array can contain any type of data. Values are comma separated and enclosed in square brackets. Positions in the array start at 0.
mixed_array = [true, 2, "three", 4.0]puts "The first element is: #{mixed_array[0]}"# Output: The first element is: true
Hashes
A collection of key-value pairs enclosed within curly braces. Values are assigned to keys using the =>
syntax.
person = {first_name: "Kara",last_name: "Brennan",age: 29}puts "#{person[:first_name]} #{person[:last_name]} is #{person[:age]} years old."# Output: Kara Brennan is 29 years old.
Symbols
Symbols are a unique data type in Ruby. They are similar to strings except that they take up less memory and have better performance. Symbols are created by using the :
syntax.
basketball_team = {:center => "Shaquille O'Neal", :forward => "LeBron James", :guard => "Steph Curry"}puts basketball_team[:center]# Output: Shaquille O'Nealputs basketball_team[:forward]# Output: LeBron Jamesputs basketball_team[:guard]# Output: Steph Curry
All contributors
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- robgmerrill124 total contributions
- christian.dinh
- Anonymous contributor
- robgmerrill
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.