Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
#Message passing
puts "the ruby language".length
puts "Ruby".index("y")
puts -6.abs
puts 10.49.round
puts 10.50.round
puts 2.next
puts 99.chr
puts
#Variables and Aliasing
person1 = "Tommy"
person2 = person1
#assigning person1 to person2 does not create an new objet. Both refer to the same object.
puts person1
puts person2
puts
#To void aliasing, and create new object with same content use dup.
person3 = person1.dup
person1[0] = "R"
puts person1
puts person2
puts person3 #new object
puts
#Chaining assignment statements
#assignment sets variable on left to experssion on right.
a = b = 1 + 2 + 3
puts a
puts b
puts
a = (b = 1 + 2) + 3
puts a
puts b
puts
#Parallel assigment
a = 1
b = 2
a,b = b,a
puts a
puts b
puts
x = 0
a, b, c = x, (x += 1), (x +=1)
puts a # x = 0
puts b # x = 0 + 1 now x = 1
puts c # x = 1 + 1 now x = 2
puts x # x = 2
puts
#Arrays
#using literals : list of objects between brackets
#arrays can hold objects of different types
a = ["number",1,2,3.14]
puts a
puts a.length
puts a[0]
a[3] = nil
puts a
puts
#Array object
#Ruby allows array range specification
myarray = [1,2,3,4,5,6]
puts myarray[0] #1
puts
puts myarray[1,3] #i to j,including j
puts
puts myarray[1...3] #i to j,excluding j
puts
puts myarray[1..3] #i to j,including j
puts
#Negative index allowed
a = ["pi", 3.14, "prime",17]
puts a.class
puts a[-1] #count from end of array
puts a[3]
puts a[-2]
puts a[2]
puts a[1]
puts a[0]
puts
b = Array.new
puts b.class
puts b.length
b[0] = "a"
b[1] = "new"
puts b.length
puts b
puts
#Associative Arrays (Hash)
#undordered collection of elements
#element is a pair of two objects:
#value and key:
#hashName = { "key" => "value",...}
biblio = { "hello" => "No",
"Salut" => "Yes",
"Tell me the gossip fam" => "maybe" }
puts biblio.length
#To retreive the value of a key:
#["key"] = value
puts biblio["hello"]
biblio["Tell me the gossip fam"] = "ok"
puts biblio["Tell me the gossip fam"]
puts
#Add to the collection
biblio["Someone is in love"] = "yas"
puts biblio["Someone is in love"]
puts biblio.length
#Delete an element
biblio.delete_if{|key, value| key == "hello"}
puts biblio.length
puts
#Iterate over an associative array
biblio.each_pair do |key,value|
puts "#{key} : #{value}"
end
puts
#Same output different way
biblio.each { |key, value| puts key + " : " + value}
puts
#Iterate over collection and access and disply each key individually
biblio.each_key {|key| puts key}
Advertisements
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.
AcceptLearn more