博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Ruby学习笔记1 -- 基本语法和数据类型, Class
阅读量:4691 次
发布时间:2019-06-09

本文共 2143 字,大约阅读时间需要 7 分钟。

Ruby 有4种数据类型:String, Boolen, Array, Hashes

Ruby 有3种操作方法:Method, attribute, ??
Ruby 有xxx: Classes, Object....

====先来看数据类型====

1. String and Declaring the variables: 

name = "Wonder Woman"   #declare a var and store a stringputs name  		#puts -- print out the varsum = 5 + 1.4puts sumcorrect = 1 == 1puts correct

2. Arrays:

cities = ["chongqing","beijing","shanghai"]puts cities[1];		#print out the SECOND city

3.Hashes:

注意这句话:We can access any value by naming its key

seasons = { "Spring" => 20, "Summer"=>30, "Autumn"=>20, "Winter"=>02}puts seasons["Winter"]#{ ? , ? , ? }# "key"# "key" => value# access: HashName[ "key" ] = value

4. Declare and Refer the variables

foods = ["apple", "pear", "orange"]puts "my favourite foods are #{foods}"# here we use #{} to refer to the variables.

5. Methods

For all object types, Ruby has a number of built in methods that allow us to change the object. Let's look at a few common ones:

    a. Strings:     .reverse, .capitalize

    b. Numbers: + , - , * , /

    c. Arrays:      .delete, .count

    d. Hashes:    .compare, .flatten

用.号来调用methods.
colors = ["oo", "tt" , "tt", "ff"]puts colors.first  # call the method .first on array

6. Define our own methods

def clock(time)	puts "It's #{time}!"endclock("10:00pm")  #note the ""

7. if ... else ... end

num = 6if num.even?  puts "This int is even."else  puts "This int is odd."end  # don't forget the end

8. Iterator - 迭代器

for Array and Hash ,使用迭代器来遍历Access each element.

names = ["Tommy","Catty","Barry","Sunny"]names.each do |nname|	puts "hello #{nname}!"end

9. Classes - 类

关于Class的声明和使用:

class Person def hello  puts "hello" endendperson1 = Person.newperson1.helloperson2 = Person.newperson2.hello

another e.g.

class Person  def initialize(name, age)    @name = name    @age = age  end   def intro    puts "My name is #{@name} and I am #{@age} years old"  endendperson1 = Person.new("Lupe", 8)person1.introclass Dog	def initialize(name,color)		@name = name		@color= color	end	def describe		puts "My name is #{@name} and I am #{@color}"	endenddog1 = Dog.new("Rover","beige")dog1.describe

posted on
2015-04-24 15:59 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/sonictl/p/6735566.html

你可能感兴趣的文章
密码框input不允许输入汉字,只可输入数字和字母等
查看>>
【2000*】【Codeforces Round #518 (Div. 1) [Thanks, Mail.Ru!] B】Multihedgehog
查看>>
日留存、周留存、月留存,究竟怎样才能让更多的用户留下来?
查看>>
Codeforces 463D Gargari and Permutations(求k个序列的LCS)
查看>>
Dedecms之SQL语句修改和调用数据总结
查看>>
遍历Panel1中所有label控件的Text
查看>>
提升内外网文件交换安全性,这里有5点建议
查看>>
第一阶段的问题总结
查看>>
sharepoint 在Visual Studio设置其他页面的加载标签
查看>>
C# 合并Excel工作表
查看>>
Python内置函数(66)——vars
查看>>
jQuery判断checkbox是否选中的3种方法
查看>>
关于oracle样例数据库emp、dept、salgrade的mysql脚本复杂查询分析
查看>>
一些有趣的代码
查看>>
从RTP到ORTP
查看>>
单文档切换OpenGL视图
查看>>
抽象类和接口的区别
查看>>
JS生成随机的字母数字组合的字符串
查看>>
[jQuery] form提交到iframe之后,获取iframe里面内容
查看>>
js new到底干了什么,new的意义是什么?
查看>>