Ruby: Basic Syntax 基础语法

Ruby Basics

Ruby is strongly typed and dynamically typed

irb # run in command line
ibj = object.new
obj.class
obj.class.superclass
obj.methods



foo = 5
# Print string
# "#{var}"
p "Hello, #{foo}!"
# Or
p 'Hello, ' + foo.to_s + '!'

def obj:talk(message, prefix="echo-")
  puts "#{prefix}#{message}"
end

obj.talk("my message")
# Or
obj.send("talk", "my message")

1 == 1.0 #=> true value equality
1.eql? 1.0 #=> false hash key equality
1.equal? 1.0 #=> false check reference equality

# EVERYTHING IS AN OBJECT!!!
# Numerics: integer and float
# -= and +=
# for loop: each, step, range
# same object_id for difference instance of 1

# String
hello << '!' # appending
#destructive methids
str.upcase # return without modifying the object
str.upcase! # return with modified object
to_s
to_i
to_f

# Symbol: string with immutable copy
a= :long # denoted with colon
to_sym

# TrueClass and FalseClass


# If Statements

foo = if true
				1
			elsif false
				2
			else
				3 
			end

# Unless Statement
unless false
  p "hello"
end

# One liners
p "hello" if true
p true ? 'hello': 'goodbye'


# Arrays and Hashes
# Array: auto-adjusted length, heterogeneous elements
a = []
a << 1
# Iterators
arr = [1,2,'john']
arr.each do |item|
  puts "#{item}"
end
arr.each_with_index do |item, i|
  puts "#{i} - #{item}"
end
# Block
[1,2,3].each {|n| print "#{n}"}
# ranges
(-5..-1).to_a #[-5,-4,-3,-2,-1]
('a'..'e').to_a #['a','b','c','d','e']
(2..100).each {|x| puts "#{x}"}
(2..100).step(2) {|x| puts "#{x}"}

#Hashes
foo = {}
foo[:hello] = "world"
p foo[:hello]
foo = {
  foo: 'bar',
  baz: 'foobar'
  }
foo.each {|key, val| puts "#{val} + #{key}"}
foo.each_with_index {|(key, val), index| puts "#index: #{val} + #{key}"}


# Methods
def hi (name)
  'hello, #{name}'
end
# return the lass excuted expression
# Mathods end in ? (return a boolean), = (write to a variable), ! (perform operation inplace on the object)

#Default argument
def hi (name = "Simon")
  'hello, #{name}'
end

#Optional argument
def hi (*name)
  p name
end
# hi() -> []
# hi(1,2,3) -> [1,2,3]

# Gems
# The Bundler Gem for managing other gems
# The Pry Gem for debuging
# The Rubocop Gem for grading for style
# The RSpec Gem
# 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值