Ruby concise learning notes (1): strings, numbers, classes and objects, ruby learning notes
To prove that Ruby is really easy to use, hello world can also be written so concisely:
Copy codeThe Code is as follows:
Puts 'Hello world'
1. Input/Output
Copy codeThe Code is 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 and is evaluated using the # {} package, enclose it with double quotation marks (if it is just a single quotation mark '', only the literal value is returned ). Not only variables, you can even embed "\ t" "\ n" and arithmetic expressions.
Copy codeThe Code is as follows:
Puts "Hello # {showname }"
Puts ("\ n \ t #{(1 + 2) * 3} \ nGoodbye ")
3. if ...... Then statement
Copy codeThe Code is 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}, so grand total is $ # {subtotal + tax }"
1. Each if object must have an end object, and then is optional, unless it is in the same line as if.
2. The to_f () method returns the floating point itself for a String with a floating point value. If the conversion fails, the system returns 0.0.
4. Differences between val, $ val, and @ val
Val is a local variable, $ val is a global variable, and @ val is an instance variable.
Instance variables are equivalent to member variables.
5. How to define a class
Read two sections of code
Copy codeThe Code is as follows:
Class Dog
Def set_name (aName)
@ Myname = aName
End
Def get_name
Return @ myname
End
Def talk
Return 'Woof! '
End
End
Copy codeThe Code is as follows:
Class Treasure
Def initialize (aName, ADEE)
@ Name = aName
@ Description = adeworkflow
End
Def to_s # override default to_s method
"The # {@ name} Treasure is # {@ description} \ n"
End
End
1. member variables must be marked @
2. The method without parameters can be left blank ()
3. end each class with end
4. There is no parameter constructor initialize () by default. You can also override initialize () with parameters ()