ruby 与 rails

《ruby 教程》ruby初探

2017-04-27  本文已影响83人  饥人谷_若愚

执行 ruby

  1. ruby 文件
# hello.rb
print("hello, Ruby .\n")
  1. 控制台用 ruby 执行文件($代表控制台执行,不是命令)
$ ruby hello.rb
  1. 直接在控制台打开 ruby 环境
$ irb

字符串

print ("hello \n world")
print ('hello \n world')

在双引号里 \是转义字符,\n会换行,在单引号里\会当成字符串输出

方法调用

print ("hello world")
print "hello world"
print "hello", "world"

方法调用参数可以省略括号

输出

print "hello world"
puts "hello world"
p "100"
p 100

print 不会换行,puts输出后换行,p 能看到原始的数据格式

编码

# encoding: GBK
print "饥人谷"

对于中文,如果文件保存的是 GBK,则需要指明编码方式为 GBK

$ ruby -E UTF-8 hello.rb
$ irb -E UTF-8

变量

a = 1.5
name = "饥人谷"
age = 3
isOk = true
obj = {"name"=>"饥人谷", "age"=>3}
p obj["name"]

变量无需声明类型

变量与双引号

width = 100
height = 200
puts "宽度: #{width}, 高度:#{height}, 面积: #{width*height}"

注释

# 这是单行注释

=begin
这是大段
注释
=end

条件判断

score = 80
if score >= 90 then
  puts "优秀"
elsif score >=80 then
  puts "良"
elsif score >=60 then
  puts "及格"
else
  puts "不及格"
end

while

i = 1
while  i<10
  puts i
  # i++   错误
  # i += 1 正确
  i = i + 1 #正确
end

times

i = 1
100.times do
  puts i
  i += 1
end
上一篇 下一篇

猜你喜欢

热点阅读