Hello, Ruby
description: Hello, Ruby! 学习 ruby 的语法知识,并且做一个 ruby 项目。 cover: https://mllmu3qmmprr.i.optimole.com/w:auto/h:auto/q:mauto/f:avif/https://www.codingclub.org/wp-content/uploads/elementor/thumbs/ruby-pnq82bm8hpfdnwihsoudyp39okf9fczjwsxjkewd54.jpg tags:
- ruby
Hello, Ruby!
![]()
Ruby Programming
[Ruby Essentials - Techotopia](https://www.techotopia.com/index.php/Ruby_Essentials)
HELLO WORLD.Ruby.
puts 'hello world,ruby.'
Strings,Numbers,Classes and Objects
puts('Enter your name:')
name = gets()
puts('hello, #{name}')
Puts string into terminal.Gets input from terminal and save to variable "name" , and puts string with variable.
If your do not want to auto add a linefeed after output, you can use
puts.
Ruby is case sensitive,myvar and myVar is difference variable.
The funny thing is, #{name}(called embedded evaluation) only works with double quotes and neither a single quote.
Next example about numbers:
subtotal = 100.00
taxrate = 0.175
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
or other version:
taxrate = 0.175
print "Enter price (ex tax): "
s = gets
subtotal = s.to_f
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
# this is a comment
=begin
This is a
multiline
comment
=end
You can do not use
()after any method, but sometimes ruby intercepted will warn you.
Here s.to_f is a method of the String class.It attempts to convert the string to a floating point number.
If the string cannot be converted, 0.0 is returned.
You can find two comment at above code.
Condition
Example:
taxrate = 0.175
print "Enter price (ex tax): "
s = gets
subtotal = s.to_f
if (subtotal < 0.0) then
subtotal = 0.0
end
tax = subtotal * taxrate
puts "Tax on $#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}"
Condition is simple like those:if (...) then ... end.
In fact, the brackets are optional, also the keyword then is optional too.But if you were to write the following, with no line break after the test condition, them then would be obligatory:
if( subtotal< 0.0 ) then subtotal = 0.0 end
Local and global variables
Variables such as these, which begin with a lowercase character, are local variables, otherwise, is a global variable.Look this example:
localvar = "hello"
$globalvar = "goodbye"
def aMethod
localvar = 10
puts( localvar )
puts( $globalvar )
end
def anotherMethod
localvar = 500
$globalvar = "bonjour"
puts( localvar )
puts( $globalvar )
end
aMethod # echo 10,goodbye
anotherMethod # echo 500, bonjour
puts localvar # echo hello (scope variable)
puts $globalvar # echo boujour (global variable)
Classes and Objects
A 'class' is the blueprint for an object.And Ruby is object oriented.
Let us create a dog class:
class Dog
def set_name(aName)
@myname = aName
end
end
The class definition begins with the keyword class(all lowercase) and the name of the class itself, which must begin with an uppercase letter.
The class contains a method set_name.This takes a incoming argument, aName.
The body of the method assigns the value of aName to variable called @myname.
Instance variables
Variables beginning with the @ charactor are instance variable,that means that they belong to individuals objects, or instance of the class.
myDog = Dog.new
yourDog = Dog.new
myDog.set_name('Aaron')
yourDog.set_name('Jay')
At the moment, these two dogs have a difference name between other.The data inside each object is private.
This is called data hiding.
Now, we need each dog to know its own name.
def getName
return @myname
end
The
returnkeyword here is optional.When it is omitted, Ruby methods will return the last expression evaluated.But for the sake of clarity, I want to keep write a clarity return value which I plan to use.
Messages,Methods and Polymorphism
Nothing.
Constructors - new and initialize
Example:
class Demo
def initialize(name, descrip)
@name = name
@descrp = descrip
end
end
When a class contains a method named initialize this will be automatically called when an object is created use the new method.
Developers often use a initialize method to set the values of an object's instance variables.
Inspecting Objects
The inspect method is defined for all Ruby Objects.It returns a string containing a humen-readable representation of the object.
Ruby also provides the p method as a shortcut to inspecting object
Class Hierarchies,Attributes and Class variables
Class Hierarchies
class Thing
def initialize(name, des)
@name = name
@des = des
end
def getName
return @name
end
def setName(name)
@name = name
end
end
class Treasure < Thing
def initialize(name, des, value)
super(name, des) # super => passes name , des and value to super class's initialize function
# super() => no pass params
@value = value
end
def value
return @value
end
def value=(v)
@value = v
end
end
Classes have own set accessors, you can not use space between set accessors code.
So this is correct:
def name=(name)
And, this is an error:
def name = (name)
But, we have a shortcut method:
class Dog
attr_reader :name
attr_writer :name
# more terse: attr_accessor :name
end
Now, you can set and get dog instance's name easily.
If you want to declare multi accessor, just like this:
class Dog
attr_reader :name, :id
attr_writer(:name, :id)
# or
# attr_accessor(:name, :id)
end
As always, in Ruby, brackets around the arguments are optional but, in my view (for reasons of clarity), are to be preferred.
Calling methods of a superclass
If you want to init some value from superclass,you need to call super method.
Class variables
The two @ characters at the start pf this variable name, @@num, define this to be a class variable.
if superclass define a class variable, then all subclass can share this variable.
CONSTANTS INSIDE CLASSES
class X
A = 10
class Y
end
end
If you want to access the constant A, you must to use the special scope resolution operator :: like this:
X::A or ob = X::Y.new!
Partial classess
In Ruby its is not obligatory to define a class all in one place.
class A
def a
puts( "a" )
end
end
class B < A
def ba1
puts( "ba1" )
end
end
class A
def b
puts( "b" )
end
end
class B < A
def ba2
puts( "ba2" )
end
end
Now,if I create a B object, all the methods of both A and B are available to it:
ob = B.new
ob.a # 'a'
ob.b # 'b'
ob.ba1 # 'ba1'
ob.ba2 # 'ba2'
You can use partial class definitions to add features onto Ruby's standard class such as Array:
class Array
def hello
puts "hello"
end
end
[1,2,3].hello # 'hello'
User-Defined String Delimiters
%Q/This is the same as a double-quoted string./ %/This is also the same as a double-quoted string./ %q/And this is the same as a single-quoted string/
Also, you can define your self string delimiters like this:
%Q[This is a string] # as "this is a string"
BACKQUOTES
Blackquotes means execute a system command.
puts(`ls`) # just like exec ls command on unix system
print("show dir: #{%x{ls}}")
String Handling
Concatenation
s = "hi" << "yo"
s = "hi" + "yo"
s = "hi" "yo"
# all echo: 'hiyo'
Puts a array will put each item in a newline,prints not.
String Assignment
s = "hello"
s[1] # prints out index 1 => e
s[-1] # o
s[1,2] # el
If you want to remove some charactor from a string.
s = "hello"
s.chop # hell
s = "hello
"
s.chop # hello
s.chomp # just remove record separator , echo hello
s.chomp('lo') # hel
Format String
Ruby provides the printf method to print format strings containing specifiers starting with a percent sign, %.
printf("%0.02f", 10.123) # 10.12
Ranges
a = (1..10)
a.to_A # [1,2,3,...,10]
b = ('b'..'e')
b.to_a # ['b','c','d','e']
Interation with range
for i in (1..3) do
puts(i)
end
# 1,2,3 with newline
Heredocs
str = <<EODOC
I am Jay.
Yo
EODOC
Arrays and Hashes
An Array is a sequential collection of items in which each item can be indexed.
In an array, each item can be difference type.
Create Arrays
In common with many other programming languages, Ruby uses square brackets to delimit an array.
arr = ['one', 'two']
puts(arr[1]) # two
Array.new # []
Array.new(2) # [nil, nil]
Array.new(2, 'a') # ['a', 'a']
Iteration over arrays
arr = [1,2,3]
for i in arr
puts(i.inspect)
end
# 1
# 2
# 3
Indexing into array
arr = ['h', 'e', 'l', 'l', 'o']
arr[0,5] # ['h', 'e', 'l', 'l', 'o']
arr[0..1] # ['h']
arr = []
a[0] = 1
a[3] = 3
print(a) # [1, nil, 3]
Copy arrays
arr1 = ['h', 'e', 'l', 'l']
arr2 = arr1
arr2[0] = 'x'
arr1 # ['x', 'e', 'l', 'l']
arr3 = arr1.clone
# arr3 is independent
Sorting arrays
arr.sort{
|a,b|,
a.to_s <=> b.to_s # if a > b, return 1,if a === b,return 0, else return -1
}
Comparing values
The comparison operator <=> (which is, in fact, a method) is defined in the Ruby module named Comparable.
Other operator:
<: less than==: equal to>: lass than
Array methods
- flatten
- compact
- <<
- clear
- delete
- delete_at
- ...
Visit here: [Most Common Ruby Array Methods You Should Know](https://www.freecodecamp.org/news/common-array-methods-in-ruby/)
Creating Hashes
h1 = Hash.new
h2 = Hash.new("some kind of ring")
h1 # {}
h1['name'] = 'Jay'
h1 # {'name': 'Jay'}
Hash map's key can be any type in principle.
Copying a hash
h1 = Hash.new
h1['a'] = 'a'
h2 = h1.clone
h2['a'] = 'aa'
h1['a'] # 'a'