2014年10月26日 星期日

[ 文章收集 ] RB Learning - Writing Own Ruby Methods

Source From Here 
Preface 
Let's look at writing one's own methods in Ruby with the help of a simple program p008mymethods.rb. Observe that we use def and end to declare a method. Parameters are simply a list of local variable names in parentheses. 

Writing Own Ruby Methods 
We do not declare the return type; a method returns the value of the last statement executed in the method. It is recommended that you leave a single blank line between each method definition. The parentheses around a method's arguments are optional; our convention is to use them when a method has arguments and omit them when it doesn't. In Rails, you will see methods calls with no parentheses. 
- p008mymethods.rb 
  1. # p008mymethods.rb    
  2. # A method returns the value of the last line    
  3. # Methods that act as queries are often named with a trailing ?    
  4. # Methods that are "dangerous," or modify the receiver, might be named    
  5. # with a trailing ! (Bang methods)    
  6. # A simple method    
  7. def hello    
  8.   'Hello'    
  9. end    
  10. #use the method    
  11. puts hello    
  12.     
  13. # Method with an argument - 1    
  14. def hello1(name)    
  15.   'Hello ' + name    
  16. end    
  17. puts(hello1('satish'))    
  18.     
  19. # Method with an argument - 2    
  20. def hello2 name2    
  21.   'Hello ' + name2    
  22. end    
  23. puts(hello2 'talim')   
The output when I ran the program on my PC was: 
Hello
Hello satish
Hello talim

Ruby lets you specify default values for a method's arguments-values that will be used if the caller doesn't pass them explicitly. You do this using the assignment operator. See example p009mymethods1.rb 
- p009mymethods1.rb 
  1. # p009mymethods1.rb    
  2. # interpolation refers to the process of inserting the result of an    
  3. # expression into a string literal    
  4. # the interpolation operator #{...} gets calculated separately    
  5. def mtd(arg1="Dibya", arg2="Shashank", arg3="Shashank")    
  6.   "#{arg1}, #{arg2}, #{arg3}."    
  7. end    
  8. puts mtd    
  9. puts mtd("ruby")  
he output when I ran the program on my PC was: 
Dibya, Shashank, Shashank.
ruby, Shashank, Shashank.

Please note that as of now, there is no way, to specify a value for the second parameter and use the default value of the first parameter! 

In the above program the interpolation operator #{...} gets calculated separately and the results of the calculation are pasted automatically into the string. When you run these lines, you don't see the #{...} operator on your screen; instead, you see the results of calculating or evaluating what was inside that operator. 

Note: Interpolation refers to the process of inserting the result of an expression into a string literal. The way to interpolate within a string is to place the expression within #{and } symbols. An example demonstrates this: 
  1. puts "100 * 5 = #{100 * 5}"    
This displays: 
100 * 5 = 500

The example p010aliasmtd.rb talks about Aliasing a method which creates a new name that refers to an existing method. When a method is aliased, the new name refers to a copy of the original method's body. If the method is subsequently redefined, the aliased name will still invoke the original implementation. 
- p010aliasmtd.rb 
  1. # p010aliasmtd.rb    
  2. # alias new_name old_name    
  3. # When a method is aliased, the new name refers    
  4. # to a copy of the original method's body    
  5.     
  6. def oldmtd    
  7.   "old method"    
  8. end    
  9. alias newmtd oldmtd    
  10. def oldmtd    
  11.   "old improved method"    
  12. end    
  13. puts oldmtd    
  14. puts newmtd  
The output is: 
old improved method
old method

Notes. 
alias creates a new name that refers to an existing method, operator, global variable, or regular expression backreference ($&, $`, $', and $+). Local variables, instance variables, class variables, and constants may not be aliased. The parameters to alias may be names or symbols.

Does Ruby allow us to write functions that can accept variable number of parameters? Yes, see the following example: 
- p011vararg.rb 
  1. # p011vararg.rb    
  2. # variable number of parameters example    
  3. # The asterisk is actually taking all arguments you send to the method    
  4. # and assigning them to an array named my_string as shown below    
  5. # The do end is a Ruby block which we talk in length later    
  6. def foo(*my_string)      
  7.   "#{my_string.class.name}:#{my_string}"    
  8. end    
  9. puts foo('hello','world')    
  10. puts foo()   
The asterisk (called the splat argument) is actually taking all arguments you send to the method and assigning them to an array named my_string. As you can see, by making use of the asterisk, we're even able to pass in zero arguments. The code above will result in the Array ['hello', 'world'] written in the first method call and an empty Array being written on the second call, as you can see in the following output: 
Array:["hello", "world"]
Array:[]

In Ruby 1.9, you can put the splat argument anywhere in a method's parameter list: 
  1. def opt_args(a,*x,b)  
What is the maximum number of parameters we can pass in Ruby? There's no limit to the number of parameters. What is the sequence in which the parameters are put on to the stack? Left to right like C or right to left like Pascal? The answer is Left to right as you can see in this example p012mtdstack.rb
- p012mtdstack.rb 
  1. # p012mtdstack.rb    
  2. # Sequence in which the parameters are put on to the stack is left to right    
  3. def mtd(a=99, b=a+1)    
  4.   [a,b].to_s    
  5. end    
  6. puts mtd      # displays: [99100]   
  7. puts mtd(49)  # displays: [4950]  
  8. puts mtd(1,2) # displays: [12]  
Are the parameters passed by value or reference? Observe the following example: 
  1. def downer(string)    
  2.   puts "downer->#{string.object_id}: #{string.downcase}"    
  3. end    
  4. a = "HELLO"    
  5. downer(a)                         # downer->2000: hello   
  6. puts "a->#{a.object_id}:#{a}"     # a->2000:HELLO    
  7.     
  8. def downer(string)    
  9.   puts "downer!->#{string.object_id}: #{string.downcase!}"    
  10. end    
  11. a = "HELLO"    
  12. downer(a)                         # downer!->2002: hello    
  13. puts "a->#{a.object_id}:#{a}"     # a->2002:hello   
Gary Wright in the Ruby forum posted in reply to some posts: "It is confusing to me to even think about methods returning objects unless you are using that as a very specific shorthand for saying that methods return *references* to objects. That is the unifying idea that helped me understand how Ruby manipulates data -- it is all references and not the objects themselves. The objects themselves are almost completely hidden from the programmer (excluding C extensionsin Ruby. Everything is a reference to an object." 

Bang (!) Methods 
Ruby methods that modify an object in-place and end in an exclamation mark are known as bang methods. By convention, the bang labels a method as dangerous - specifically, as the dangerous equivalent of a method with the same name but without the bang. 

You'll find a number of pairs of methods, one with the bang and one without. Those without the bang perform an action and return a freshly minted object, reflecting the results of the action (capitalizing a string, sorting an array, and so on). The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object. 

Examples of such pairs of methods include sort/sort! for arrays, upcase/upcase! for strings, chomp/chomp! for strings, and reverse/reverse! for strings and arrays. In each case, if you call the non-bang version of the method on the object, you get a new object. If you call the bang version, you operate in-place on the same object to which you sent the message. 
In Ruby you can define a method name that ends with an exclamation point or bang. The bang methods are called and executed just like any other method. However, by convention, a method with an exclamation point or bang is considered dangerous.

Normally for the built-in classes, dangerous usually (although not always) means this method, unlike its non-bang equivalent, permanently modifies its receiver.

You'll find a number of methods, one with the bang and one without. Those without the bang perform an action and return a new object. The bang versions of the same methods perform the action, but they do so in place: Instead of creating a new object, they transform the original object.

A few non-bang methods perform changes on the original string. The names of these methods make it clear that this is happening (such as replace), even though there's no ! on the name.

Method names ending with ? 
The question mark has no special meaning to the Ruby interpreter. However, by convention, any method whose name ends with ? returns a value that answers the question posed by the method invocation. The empty? method of an array, for example, returns true if the array has no elements. Mostly such methods return one of the Boolean valuestrue or false, but this is not required, as any value other than false or nil works like true when a Boolean value is required. The Numeric method nonzero?, for example, returnsnil if the number it is invoked on is zero, and just returns the number otherwise. 

Summary 
I have listed down all the important points you need to remember after you have completed the following topics: ScopeGetting InputRuby NamesMore on Ruby MethodsWriting on Ruby Methods.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...