文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Ruby 基本语法(一)【原创】  


Ruby 基本语法

# 表示注释

 

puts “hello phper.yang” #echo 输出

 

 

=begin

Ruby rails

=end

多行注释

 

 

变量:x = 10

局部变量:ap = 100 _b = 100 小写字母或者下划线开头

实例变量:@a = 100

类变量:@@a = 100

全局变量:$a = 100

常量:Ma = 1 首字母大写或全部大写

 

if 1 == 1 then

   print “True”

end

 

if queue

   print ‘true’

else

   print ‘false’

end

 

if lang

elsif …

end

 

case cc

  when 0:

puts ‘a’

  when 1..3:

puts ‘b’

  else

puts ‘c’

end

 

while i < a.size do

   print i

   i += 1

end

 

begin

   print tmp

   tmp += 1

end while tmp < 20

 

 

while i < phperyang.size

print i

break if i == 8

i += 1

end

 

if lang == ‘de’

dog = ‘hua’

else

dog = ‘hua1’

end

 

unless lang == ‘de’

dog = ‘hua1’

else

dog = ‘hua’

end

 

loop do

print ‘type’

line = gets

break if line == /q|Q/

puts line

end

 

for i in 1..5 do

    puts i

end

 

 

10.times { |i| print i}

 

1.upto(10) { |i| print i}

 

以上输出1,2,3,4,5

 

5.downto(1) { |i| print i }

以上输出5,4,3,2,1

 

title = ‘phper.yang’

puts title.empty?

puts title.size or puts title.length

 

a = <<yang

I Love Ruby

Yang

puts a

 

链接字符串相邻的就可以链接或者用 + 或者用 << 或者用 concat 方法 但是只能链接字符串。

 

phperyang = “hello,ruby”

phperyang.freeze #冻结字符串禁止修改

phperyang.concat(‘!!!’) #报错

 

a = ‘php and ruby !’

puts a[12] = 33

puts a[12].chr = !

puts a[/a/,0] 0的位置开始匹配

puts a.index(‘p’) # 0

 

puts a[a.inex(‘k’)] #107

puts a[a.index(‘k’)].chr # k

 

a = 'php'

b = 'ruby'

puts a.eql?b #false

 

puts “php ” * 2 #php php

puts "hello phper.yang".insert 6, " love " * 3 #hello  love  love  love phper.yang

 

chop chop!去掉最后一个字符

 

puts ‘hello Beijing!’.delete “o”

 

puts ‘I love php,python,ruby,c#’.gsub “c#”,”c++” 替换

puts ‘ruby’.reverse 反转

从字符串到数组

012345”.split(//)

从数组变字符串

sz = ['php','ruby','python']

puts sz.join("@")

 

a = ['php','ruby','python']

a.each do | v |

   puts v

end

puts '-------------'

a = %w(php python ruby java)

a.each_with_index do |s,i|

  puts "#{s} at index #{i}"

end

 

php

ruby

python

-------------

php at index 0

python at index 1

ruby at index 2

java at index 3