Ruby Learning-First chapter

Source: Internet
Author: User

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}
   
     "
   
    1. Each if must have an end corresponding to it, and then optional, unless it is on the same line as if.
    2. 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
    1. The member variable needs @ Mark
    2. No parameter method can be added ()
    3. Each class will end with end
    4. The default is the parameterless constructor initialize (), or you can override the Initialize () with parameters

Ruby Learning-First chapter

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.