栏目分类:
子分类:
返回
文库吧用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
文库吧 > IT > 软件开发 > 后端开发 > Ruby开发

ruby语法学习层面的先见之明

Ruby开发 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ruby语法学习层面的先见之明

看了几天ruby,发现c#中很多一直被称道的语法特性,ruby早在几年前就有了:

 1.c#中的params关键字

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;
    }
}

对应的ruby版本:

def sum(*num)
    numSum = 0
    num.each { |i| numSum+=i }
    return numSum
end
 
puts sum()
puts sum(3,6)

2.c#中的缺省参数(据说从4.0才开始支持,但ruby早就有了)

def  sum( a, b=5 )
  a+b
end
puts sum(3,6)
puts sum(3)

3.c#中的匿名方法

List lst = new List() { 1, 2, 3, 4, 5 };
lst.ForEach((i) => { Console.WriteLine(i); });

ruby中的类似语法:

(1..5).each{|x| puts x}

4.c#中的delegate与action

class Program
    {
        static void Main(string[] args)
        {
            Action a = new Action(HelloWorld);
 
            a("jimmy");
 
            Console.ReadKey();
        }
 
        static void HelloWorld(string name) 
        {
            Console.WriteLine("hello,{0}", name);
        }
    }

ruby中的类似语法:

def action(method,name) #相当于c#中的action声明部分
    method.call(name)
end
 
helloWorld = proc{|name| puts "hello,#{name}"} #被action调用的方法体
 
action(helloWorld,"jimmy"); #通过action,调用helloWorld方法,输出 hello,jimmy

5.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);
          }
      }
  }

ruby中的扩展方法更强大:

class Array
    def NewMethod
        for i in 0...size
            yield(self[i])
        end
    end
end
 
arr = [1,2,3,4,5]
 
arr.NewMethod{|x| print x ,"n"};
 
puts "*******************************"
arr.NewMethod{|x| print x * x ,"n"};


转载请注明:文章转载自 www.wk8.com.cn
本文地址:https://www.wk8.com.cn/it/226401.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 wk8.com.cn

ICP备案号:晋ICP备2021003244-6号