试图了解ruby的复杂性,但到目前为止没有任何意义。
5.times(method(:puts))
给出错误,这没有任何意义。我是否有某种语法错误,或者无法在ruby中进行?
ArgumentError: wrong number of arguments (given 1, expected 0)
from (irb):78:in `times'
我正在尝试做类似的事情
[0, 1, 2, 3, 4].forEach(console.log)
和
java.util.stream.IntStream.range(0, 5).forEach(System.out::println);
这些同时起作用:
method(:puts).call(1)
# and
5.times { |i| puts i }
答案 0 :(得分:4)
using System;
using System.Web;
using System.Linq;
namespace Sample
{
public class VersionModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += OnContextBeginRequest;
}
private void OnContextBeginRequest(object sender, EventArgs e)
{
try
{
HttpApplication app = (HttpApplication)sender;
if (app.Context.Request.Cookies.AllKeys.Contains("version"))
{
string newUrl = @"https://sample.com/v";
var cookie = app.Context.Request.Cookies.Get("version");
if (!string.IsNullOrEmpty(cookie.Value))
{
if (cookie.Value == "2")
{
newUrl += "2";
string parameters = app.Context.Request.Url.PathAndQuery.Replace("v/", "");
newUrl = newUrl + parameters;
// this call alway a GET!! I need a POST method!
app.Context.Response.Redirect(newUrl, true);
}
}
}
}
catch (Exception ex)
{
}
}
public void Dispose()
{
}
}
}
接受一个块参数,该参数与“常规”参数之间用&符区分开。您可以将其传递给显式块
times
或者您可以使用5.times { |x| puts x }
&
对block参数进行不同的处理允许我们编写外观和行为与内置语句非常相似的方法。例如,Ruby中的无限循环可以写为
5.times(&method(:puts))
但是loop
是核心库中的方法,而不是内置关键字。我们可以写成loop {
# fun stuff happening in here
}
自己起作用。 loop
和其他模块大量使用了块参数来提供更友好的语法,这是Ruby作为一种语言的主要目标之一。