Ruby 7-day entry (2 functions, arrays and classes), ruby 7-day

Source: Internet
Author: User

Ruby 7-day entry (2 functions, arrays and classes), ruby 7-day
DAY 2

Continue the next day. Today we will focus on the basic elements of functions, collections, classes, and other programming.

2.1 simple definition of function 2.1.1
 def tell_me puts true end
  • Defining a simple function (No parameter and no return value) is simple. Use def end to wrap the function body.
2.1.2 Parameters
def tell_me(a)puts aendtell_me 11=> nil
  • Using parameters is similar to other languages, you can add variable names in parentheses.
2.1.2.1 parameter Default Value

You can also specify the default value of the parameter:

def tell_me(a='1',b)puts aputs bend=> niltell_me 212=> niltell_me 3,434=> nil

We can see that the method for specifying the default value is similar to that in other languages.

It seems that we need to remember the number and meaning of parameters for each function.

2.1.2.2 variable parameters

Ruby also supports variable parameters and is quite free to use because it is not subject to type restrictions:

def test(*tt)    for i in 0...tt.length        puts tt[i]    endend=> niltest 1,212=> 0...2test 'a'a=> 0...1
  • We can see that you only need to add * Before the parameter, and the received parameter will be an array.
2.1.3 return value 2.1.3.1 default Return Value
  • I saw in my study yesterday that all Ruby statements have returned values. In fact, if we don't specify the return value for the function in time, the function will return the value of the last statement executed by the function.
    See the following example:
def give_metrueend=> nili=give_me=> truei=> true

The return value is not specified for this function, but the function returns the value of true for the last executed statement.

2.1.3.2 return Statement
$ irbdef testa=1b=2return a,bend=> nilvar=test=> [1, 2]var.class=> Arrayvar=> [1, 2]
  • Ruby can use the return statement to specify the return value. Different from the C family, Ruby can return multiple return values at the same time.

  • Because of the Dynamic Language Features, Ruby looks so free, but it seems that this requires callers to be responsible for their calls.

Code block 2.2 and yield2.2.1

A code block is a function without a name.

3.times{puts 'hi'}
  • Times is the method of the Fixnum class. It can execute the subsequent code block n times.
  • The content in the braces below is a code block. The code block can be wrapped either with {} or with do/end, just like the following code.
3.times doputs 'hello'end

The each function mentioned in the interval section yesterday is actually a code block:

names=['lee','tom','jim']names.each{|a| puts a}
2.2.2 yield Execution code block

Next let's take a look at the custom method to execute the code block:

def my_times(i=5)    while i>0        i=i-1        yield    endendmy_times(3){puts 'a'}

We can see that this function calls a certain number of code blocks based on input parameters.

  • The yield defined in the function indicates the code in the Execution code block.
2.2.3 code block as function parameter

We can also keep passing the code block as a parameter.

def call_block(&block)    block.callenddef pass_block(&block)    call_block(&block)endpass_block{puts 'hello'}
  • In Ruby, a "&" is added before the parameter name to pass the code block to the function as a closure. The closure is to wrap the functions and variables to extend the life cycle of the variables.
Array 2.3
animals = ['lions', 'tigers', 'bears']puts animals[1]puts animals[-1]puts animals[0..1]
  • The above code has a syntactic sugar.-1 indicates that the last-to-last element is returned. Of course, 1 indicates the second element, just like other languages.
  • Animals [0 .. 1] uses the interval learned yesterday to indicate the elements from 0 to 1.
irb(main):002:0> [].class=> Arrayirb(main):003:0> a =[]=> []irb(main):004:0> a[1]=> nilirb(main):005:0> b[1]NameError: undefined local variable or method `b' for main:Object        from (irb):5        from /usr/bin/irb:12:in `<main>'irb(main):006:0> a[1] = 1=> 1irb(main):007:0> a[0] = 'zero'=> "zero"irb(main):009:0> a[2]=['2','3',[4,5]]=> ["2", "3", [4, 5]]irb(main):010:0> a=> ["zero", 1, ["2", "3", [4, 5]]]irb(main):011:0> a[2][2]=> [4, 5]irb(main):012:0> a[2][2][1]=> 5irb(main):021:0> a=[]=> []irb(main):022:0> a[1]=8=> 8irb(main):023:0> a[3]=6=> 6irb(main):024:0> a=> [nil, 8, nil, 6]

Compared with arrays in most languages, Ruby arrays are free to use. The code above can be seen.

  • Array elements do not have to have the same type
  • Only some array elements can be defined, and the nil value will be used for other positions by default.
  • Note that when assigning values to an array element, you must first use a = [] similar syntax to change the type to the array type, otherwise, the error message "B [1]" appears.
irb(main):025:0> a.push(4)=> [nil, 8, nil, 6, 4]irb(main):026:0> a.pop=> 4irb(main):027:0> a=> [nil, 8, nil, 6]

The array also supports push and pop, and the stack is located at the end of the array.

2.3.4 hash

A hash is a key-value pair that corresponds to the map container in java.

irb(main):032:0> map={1=>'one',2=>'two'}=> {1=>"one", 2=>"two"}irb(main):033:0> map=> {1=>"one", 2=>"two"}irb(main):034:0> map[1]=> "one"irb(main):035:0> map[3]=> nil

In fact, similar to arrays, the key difference lies in a => symbol, which is preceded by a key and followed by a value.

map={1=>'one',2=>'two'}a = map.to_aputs a
  • A hash can be converted into an array. Each element is an array consisting of a key and a value.
map.each { |k,v| p "#{k}=>#{v}"  }

The hash can also be traversed.

2.5 categories

All classes have a common ancestor, BasicObject.

class TreeTestattr_accessor :children,:node_namedef initialize(name,children=[])    @children = children    @node_name = nameendendruby_tree = Tree.new("ruby",[Tree.new('1'),Tree.new('2')])

The code above defines a simple class.

  • Class naming generally uses the camel naming method. Variables and method names use the lowercase underline naming method, while constants use the full capital format. What functions are generally used for logical testing? End
  • Add @ (similar to java's this?) before the instance variable ?), Before the class variable, add @ (similar to the java class name ?)
  • The attr keyword can be used to define instance variables. It has several versions. The most common versions are attr and attr_accessor. Attr defines the methods with the same name as the instance variables and access variables, while attr_accessor defines the instance variables, access methods, and setting methods.
  • The initialize method has a special meaning. A class calls this method when initializing a new object.
  • Class initialization uses the class name plus. new Method to initialize
Conclusion 2.6

Today, I learned the basic usage of Ruby functions, classes, and arrays. The biggest feeling is that Ruby's implementation is full of intuitive features. After mastering the basic syntax, A lot of code can be executed only by writing as you try.

2.7 practices

Today, based on the previous Tree class, I added the traversal access function. At the same time, I modified the initialization method to accept the structure of the hash list and array nesting:

class Treeattr_accessor :children,:node_namedef initialize(map={})    @children = []    map.each do |k,v|         @node_name = k        v.each { |key,value|  @children.push(Tree.new({key=>value}))} if v!=nil    endenddef visit_all(&block)    visit(&block)    children.each{|c| c.visit_all(&block)}enddef visit(&block)    block.call(self)endendruby_tree = Tree.new({'grandpa' => { 'dad' => {'child 1' => {}, 'child 2' => {} }, 'uncle'=> {'child 3' => {}, 'child 4' => {} } } } )ruby_tree.visit {|node| puts node.node_name}ruby_tree.visit_all {|node| puts node.node_name}

The visit method passes the code block, calls the code block, and uses self as the parameter (so it seems that the code block obtains the parameter in this way ?), Actually, the node_name of the called instance is printed.
Visit_all first calls the visit method on the current node, and then recursion on the child node.

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.