Ruby学习笔记(2) ————Ruby语法入门

来源:互联网 发布:js触发select 下拉框 编辑:程序博客网 时间:2024/06/16 01:51

前言:这里我把学习ruby的笔记放在这里,大家共同进步,也可以让我随时来复习。微笑

在安装好ruby的环境之后,我们就可以来敲ruby代码了,首先我们先来个hello,world(每学一门语言,都是hello,world)

在ruby里有irb调试,不过我们推荐创建.rb文件,因为irb不能写好之后一块运行,一行一行敲,太麻烦了。。。

1:输出hello,world

说明:这里我们首先创建一个空文件,hello.rb,然后打开编辑,我这里用的vim编辑器,当然大家可以自行选择,如sublime等。。。




打上puts "hello,world",然后运行ruby  hello.rb命令来输出即可

解释:用puts来进行输出,这里我们就区分p,print,puts的区别了,大家可以单独进行搜索。

2:字符串插值

在ruby中,我们最好在所有的地方都用字符串插值,避免使用+的方式

原因:不同的数据类型,使用+会报错

2.1:两种方式都可以,因为都是字符串,这里我用irb来掩饰,方便看出错误


2.2:不同类型,一个字符串,一个数字(这里会报类型转换的错,而#{*}却不会)


3:变量

类变量: class variable, 例如: @@name, 作用域:所有的多个instance 会共享这个变量。

实例变量 instance variable, 例如: @color, 作用域仅在instance之内。

普通变量: local variable, 例如: age = 20, 作用域仅在 某个方法内。

全局变量: global variable, 例如:$name = "railsboy", 作用域在全局。


代码版:

class Apple  @@from = 'China'  def color = color    @color = color  end  def color    return @color  end  def get_from    @@from  end  def set_from from    @@from = from  endendred_one = Apple.newred_one.color = 'red'puts red_one.color# => 'red'red_one.set_from 'Japan'puts red_one.get_from# => 'Japan'green_one = Apple.newgreen_one.color = 'green'puts green_one.color# => 'green'puts green_one.get_from# => 'Japan'

图文版:


4.类方法与实例方法(记住类方法就是直接用方法名输出,而实例方法需要类.new.方法名)


代码版:

class Apple  # 类方法  def Apple.name    'apple'  end  # 实例方法  def color    'red'  endendApple.new.color# => redApple.name# => apple

图文版:


5.条件语句

#if else end 是最常见的a = 1if a == 1  puts "a is 1"elsif a == 2  puts "a is 2"else  puts "a is not in [1,2]"end

#case when end 分支语句#例如:a = 1case a  when 1 then puts "a is 1"  when 2 then puts "a is 2"  when 3,4,5 then puts "a is in [3,4,5]"  else puts "a is not in [1,2,3,4,5]"end


#三元表达式a = 1puts a == 1 ? 'one' : 'not one'# => one



待续。。。。


1 0
原创粉丝点击