Ruby functions

2.2.1 :039 > def hello(str="ikbhal")
2.2.1 :040?>   "hello #{str}"
2.2.1 :041?>   end
 => :hello 

2.2.1 :042 > hello 

2.2.1 :043 > "ab cde f".split
 => ["ab", "cde", "f"] 
2.2.1 :044 > arr = [23, 45, 56]
 => [23, 45, 56] 
2.2.1 :045 > a[0]

2.2.1 :047 >   arr[0
2.2.1 :048?>   ]
 => 23 
2.2.1 :049 > arr[-1]
 => 56 

2.2.1 :050 > arr.first
 => 23 
2.2.1 :051 > arr.second
 => 45 
2.2.1 :052 > arr.third
 => 56 
2.2.1 :053 > arr.last
 => 56 

2.2.1 :059 >   arr.reverse
 => [56, 45, 23] 
2.2.1 :060 > arr
 => [23, 45, 56] 
2.2.1 :061 > arr.reverse!
 => [56, 45, 23] 
2.2.1 :062 > arr
 => [56, 45, 23] 
2.2.1 :063 > 

2.2.1 :063 > arr.shuffle
 => [23, 45, 56] 
2.2.1 :064 > arr.shuffle!
 => [23, 56, 45] 
2.2.1 :065 > arr
 => [23, 56, 45] 

2.2.1 :066 > arr.push(1001)
 => [23, 56, 45, 1001] 
2.2.1 :067 > arr
 => [23, 56, 45, 1001] 
2.2.1 :068 > arr<<"ikbhal"<<"basha"
 => [23, 56, 45, 1001, "ikbhal", "basha"] 
2.2.1 :069 > arrr.join

2.2.1 :075 >   (0..9).to_a
 => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
2.2.1 :076 > a=%w[ikbhal basha shaik]
 => ["ikbhal", "basha", "shaik"] 
2.2.1 :077 > a[0..1]
 => ["ikbhal", "basha"] 

2.2.1 :078 > (0..9).each{|i| puts 2*i}
0
2
4
6
8
10
12
14
16
18
 => 0..9 

>> 3.times { puts "Betelgeuse!" }   # 3.times takes a block with no variables.
"Betelgeuse!"
"Betelgeuse!"
"Betelgeuse!"
=> 3
>> (1..5).map { |i| i**2 }          # The ** notation is for 'power'.
=> [1, 4, 9, 16, 25]
>> %w[a b c]                        # Recall that %w makes string arrays.
=> ["a", "b", "c"]
>> %w[a b c].map { |char| char.upcase }
=> ["A", "B", "C"]
>> %w[A B C].map { |char| char.downcase }
=> ["a", "b", "c"]

No comments:

Post a Comment