some basic ruby refers to ruby-doc-1 reviews

String interpolation

String interpolation only works within double quotes:

1
2
3
4
5
6
7
8
9
10
11
12
a = 'ten'
=> "ten"
2.3.1 :002 > "my favoutite number is #{a}!"
=> "my favoutite number is ten!"
2.3.1 :003 >
2.3.1 :029 > "john" + "Doe"
=> "johnDoe"
2.3.1 :030 > a = "Doe"
=> "Doe"
2.3.1 :031 > "John#{a}"
=> "JohnDoe"

number

integer & float

float is a number that contains a decimal:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# division
2.3.1 :013 > 15 / 4
=> 3
#modulo
2.3.1 :014 > 15 % 3
=> 0
2.3.1 :015 > 15 % 4
=> 3
#float
2.3.1 :016 > 15.0 / 4
=> 3.75
2.3.1 :017 > '4'.to_i
=> 4
2.3.1 :018 > '4'.to_f
=> 4.0
2.3.1 :019 > "4 here test".to_f
=> 4.0
2.3.1 :020 > "here test 4".to_f
=> 0.0

Array & Hash index

elements within an array can be retrieved by their index,which starts at 0

1
2
3
4
2.3.1 :021 > [1,2,3,4,][0]
=> 1
2.3.1 :022 > [1,2,3,4,][3]
=> 4

also:

1
2
3
4
2.3.1 :023 > {:a => '1', :b => '2', :c => '3'}[a]
=> nil
2.3.1 :024 > {:a => '1', :b => '2', :c => '3'}[:a]
=> "1"

Array & Hash map

The map method can be used to create a new array based on the original array, but with the values modified by the supplied block:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2.3.1 :032 > arr = [1,2,3]
=> [1, 2, 3]
2.3.1 :033 > arr.map { |a| 2*a}
=> [2, 4, 6]
2.3.1 :034 > arr
=> [1, 2, 3]
2.3.1 :035 > arr.map! {|a| 2*a }
=> [2, 4, 6]
2.3.1 :036 > arr
=> [2, 4, 6]
2.3.1 :037 > ['1','2','3'].map(&:to_i)
=> [1, 2, 3]
#same as
2.3.1 :038 > ['1','2','3'].map{ |i| i.to_i}
=> [1, 2, 3]

Variable

varibale scope

inner scope can access variables initialized in an outer scope,bu not vice versa

eg

1
2
3
4
5
6
7
8
9
10
11
12
13
14
x = 0
3.times do
x += 1
end
puts x
#prints 3 to the screen
y = 0
3.times do
y += 1
x = y
end
puts x
# cant print, errors undefined local variable or method cuz x is not avaiavle as it is created with in the scope of the do/end block ,so its inner scope that's entirely outside of the execution flow.

variable type

constant variable NAME
global variable $name
class variable @@name
instance variable @name
local variable name

some other e.g..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ruby name.rb
puts "What is your name?"
name = gets.chomp
puts "Hello " + name
#ruby name2.rb
puts "what is your first name?"
first_name = gets.chomp
puts "what is your last name?"
last_name = gets.chomp
puts "Great. so your full name is " + first_name + " " + last_name
#ruby age.rb notice .to_i
puts "how old are you?"
age = gets.chomp.to_i
puts "in 10 years you will be:"
puts age + 10
puts "in 20 years you will be:"
puts age + 20