ลองเขียน Ruby ดูเล่นๆ

February 13, 2014 2:15 pm Network, Ruby

พอดีเรียน Network แล้วมีการสอน Basic Ruby ลองดู ว่าวันเดียว พื้นฐานได้หมดแหละ ลองดูกันๆ

 

Hello World

puts "Hello, World"

Convert Variable

puts 100 
puts "We have " + 2.to_s + " care." #Convert Integer to String
 
a = "100"
b = 200
 
puts a.to_i+b #Convert String to Integer

Array and Show Variable Message in “Put” and “print”

c = [100]
d = [1,2,5]
 
puts c
puts d[1]
puts "d[0] = #{d[0]}"

If Else

q = 1
if q==1
  puts "found"
else
  puts "not found"
end

Function Creater and use

def add(first,second)
  puts "Processing"
  first**second
  end
 
def stat(a,b,c)
  sum = a+b+c
  avg = (a+b+c)/3
  [sum,avg]
end
 
w = 2
e = 5
 
w,e = e,w
 
puts w
puts e
 
puts add(2,4)
puts stat(1,2,3)

Loop while

o = 1
while o

Loop Number Condition

1.upto(1000000) { |x| puts x }

Number Format Setter

puts w/e
puts 5/3.0

String Function

str = "A"
puts str
 
str = str + "B"
puts str
 
str << ?B
puts str
puts str.length
 
str = "hello"
while (str["l"])
  str["l"] = "L"
  end
 
puts str

Autoformat

print ('9'..'300').to_a
100.times { print "Death" }
 
i = [3,2,1]
 
i.each do |x|
  print x
  print " "
end