Chapter I.
strings, numbers, classes, and objects
To prove that Ruby is really good, Hello world can also be written in such a concise way:
' Hello World '
1. Input/output
Print ('Enter your name') name=gets () puts ("Hello #{name} ")
Note: Ruby is a big and small write
2.String class
The variable name in puts ("Hello #{name}") is embedded in the entire string, evaluated inline through the #{} package, and wrapped with a double quote "" (if only single quotation marks "will return literal values.) Not only are variables, you can even embed "\ t" and "\ n" and arithmetic expressions.
" Hello #{showname} " "\n\t#{(1+2) * 3}\ngoodbye" )
3.if......then statements
Print " "== s.to_f if (Subtotal < 0.0) then = 0.0 = Subtotal *"$#{subtotal} is $#{tax}, so grand total is $#{subtotal+tax}
"
- Each if must have an end corresponding to it, and then optional, unless it is on the same line as if.
- The To_f () method returns the floating-point number itself for a string that has a value of floating-point numbers, and returns 0.0 for a person who cannot convert
4.val, $val, @val differences
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 the two pieces of code
class Dog def Set_name (aName) @myname = AName End def get_name return @myname end def talk return " woof! EndEnd
class Treasure def Initialize (aName, adescription) @name = aName @description = adescription End def # override default to_s method " The #{@name} treasure is #{@description}\n " endend
- The member variable needs @ Mark
- No parameter method can be added ()
- Each class will end with end
- The default is the parameterless constructor initialize (), or you can override the Initialize () with parameters
Ruby Learning-First chapter