31
loading...
This website collects cookies to deliver better user experience
print "Hello World!!!"
PS D:\Workplace> ruby hello-world.rb
Hello World!!!
print "\n" equals puts
print "First line "
print "still first line\n"
puts "Second line"
puts "Thirld line"
First line still first line
Second line
Thirld line
print else
main
check whether the num is even or odd
num = 2
print num.even?
true
print the quotient of num and 2
num = 2
num.div 2
print num
1
print the value of each member in array to the power of 2
array = [1, 2, 3, 4, 5]
array.each do |num|
puts num.pow 2
end
1
4
9
16
25
print ASCII chars of any decimal number in array if number is not odd
def print_char(array)
array.each do |num|
puts num.chr unless num.odd?
end
end
array = [65, 66, 67, 68, 69, 70, 71]
print_char(array)
B
D
F
Delete last element
arr.pop
Delete first element
arr.shift
Delete element at position a given position
arr.delete_at(2)
Delete all occurrences of a given element
arr.delete(5)
Delete elements if
arr.delete_if {|a| a < 2}
Delete elements unless
arr.keep_if {|a| a < 4}
Select elements from array to subarray
arr2 = arr.select {|a| a > 2}
print arr2
Reject elements from array to subarray
arr2 = arr.reject {|a| a > 2}
Reject elements from array till returns false for the first time
arr2 = arr.drop_while {|a| a > 1}
# initialize and set default value
empty_hash = Hash.new
empty_hash.default = 1
# or
default_hash = Hash.new(1)
new_hash = {"key1" => 12, "key2" => 50}
# or
new_hash = Hash.new
new_hash["key1"] = 12
new_hash["key2"] = 50
# or
new_hash.store("key1", 12)
new_hash.store(1512032, 50)
hash.each do |key, value|
puts key
puts value
end
# or
hash.each do |array|
# now key is array[0], value is array[1]
puts array[0]
puts array[1]
end
# Delete specific key
hash.delete("key1")
# Delete if
hash.keep_if {|key, value| key.is_a? Integer}
# or
hash.delete_if {|key, value|key.even? }
i = 0
loop do
puts i
i += 1
break if i == 10
end
1
2
3
4
5
6
7
8
9
10
Thanks for reading my blog