前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ruby学习笔记(3)--语法层面的先见之明

ruby学习笔记(3)--语法层面的先见之明

作者头像
菩提树下的杨过
发布2018-01-22 16:00:54
5700
发布2018-01-22 16:00:54
举报

看了几天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<int> lst = new List<int>() { 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<string> a = new Action<string>(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"};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2010-02-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档