To prove that Ruby really works, Hello World can write so succinctly:
Copy Code code as follows:
1. Input/output
Copy Code code as follows:
Print (' Enter your name ')
Name=gets ()
Puts ("Hello #{name}")
Note: Ruby is case-sensitive
2.String class
The variable name in puts ("Hello #{name}") is embedded in the entire string, evaluated by the #{} package, and wrapped in double quotes "" (If only single quotes "only returns the literal value)." Not only are variables, you can even embed "T" "\ n" and an arithmetic expression.
Copy Code code as follows:
Puts "Hello #{showname}"
Puts ("\n\t#{(1+2) * 3}\ngoodbye")
3.if......then statement
Copy Code code as follows:
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}
1. Each if must have an end corresponding to it, and then optional unless it is on the same line as if.
The 2.to_f () method returns the floating-point number itself for a string with a value of floating-point numbers, which returns 0.0 for the person who cannot convert
The difference between 4.val, $val, @val
Val is a local variable, $val is a global variable, @val is an instance variable
Instance variables are equivalent to member variables
5. How to define a class
Look at two pieces of code
Copy Code code as follows:
Class Dog
def set_name (Aname)
@myname = Aname
End
def get_name
Return @myname
End
Def talk
Return ' woof! '
End
End
Copy Code code as follows:
Class Treasure
Def initialize (Aname, adescription)
@name = Aname
@description = Adescription
End
def to_s # Override default To_s method
"The #{@name} treasure is #{@description}\n"
End
End
1. Member variable needs @ Mark
2. No parameter method can be added without ()
3. Each class ends with end
4. The default has no parameter constructor initialize (), or you can override initialize with parameters ()