After reading Ruby for a few days, I found many well-known syntax features in C #. Ruby was available a few years ago:
1. The Params keyword in C #
Class program {static void main (string [] ARGs) {console. writeline (sum (); console. writeline (sum (3, 6); console. read ();} static int sum (Params int [] Nums) {int _ result = 0; foreach (INT item in Nums) {_ result + = item ;} return _ result ;}}
Corresponding Ruby version:
Def sum (* num) numsum = 0num. Each {| I | numsum + = I} return numsumendputs sum () puts sum (3, 6)
2. default parameters in C # (it is said that they are supported only from 4.0, but Ruby has long been available)
Def sum (a, B = 5) A + bendputs sum (3, 6) puts sum (3)
3. Anonymous method in C #
List <int> lst = new list <int> () {1, 2, 3, 4, 5}; lst. foreach (I) => {console. writeline (I );});
Similar syntax in Ruby:
(1 .. 5). Each {| x | puts x}
4. Delegate and action in C #
Class program {static void main (string [] ARGs) {Action <string> A = new action <string> (helloworld); A ("Jimmy"); console. readkey ();} static void helloworld (string name) {console. writeline ("Hello, {0}", name );}}
Similar syntax in Ruby:
Def action (method, name) # is equivalent to the partial method declared by action in C. call (name) endhelloworld = proc {| Name | puts "Hello, # {name}"} # action (helloworld, "Jimmy "); # Call the helloworld method through action to output Hello, Jimmy
5. Extension Method in C #
Class program {static void main (string [] ARGs) {int [] arr = new int [] {1, 2, 3, 4, 5}; arr. newmethod (); console. readkey () ;}} public static class extendutils {public static void newmethod (this array ARR) {foreach (VAR item in ARR) {console. writeline (item );}}}
More powerful extension methods in Ruby:
Class arraydef newmethodfor I in 0... sizeyield (Self [I]) endendendarr = [1, 2, 4, 5] arr. newmethod {| x | print X, "\ n "}; puts "********************************" Arr. newmethod {| x | print x * X, "\ n "};