为什么空白会影响 ruby​​ 函数调用? [英] Why does white-space affect ruby function calls?

查看:50
本文介绍了为什么空白会影响 ruby​​ 函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码出现语法错误

render json: {
    "what" => "created", 
    "whatCreated" => "thing",
    "htmlOutput" => render_to_string (partial: "some_partial")
}

但使用此代码我不会:

render json: {
    "what" => "created", 
    "whatCreated" => "thing",
    "htmlOutput" => render_to_string(partial: "some_partial")
}

render_to_string 破坏我的 Rails 应用程序后,那个空间怎么来的?

How come that space after render_to_string breaks my rails app?

推荐答案

问题是,ruby 中的方法可以带或不带括号运行.例如,您可以运行 Array.new 1,2 并且 ruby​​ 知道它接收空格后的参数.你也可以运行 Array.new(1,2) 并且 ruby​​ 知道参数在括号内.

the thing is, that method in ruby can be run with or without parentheses. for example, you can run Array.new 1,2 and ruby knows that it receives the arguments after the space. and you can also run Array.new(1,2) and ruby knows the args are inside the parentheses.

但是,当你运行 Array.new (1,2) 时,ruby 认为它会在空格后接收参数,但实际上它接收的是一个元组 (1,2),基本上和 Array.new((1,2))

but, when you run Array.new (1,2) , ruby thinks it will receive arguments after the space but actually it receives a tuple (1,2), and basicaly its exactly the same as Array.new((1,2))

所以底线:

Array.new (1,2) == Array.new((1,2)) 这是一个语法错误,因为 (1, 2) 文字不是有效的

Array.new (1,2) == Array.new((1,2)) and thats a syntax error because (1, 2) literal is not a valid one

这篇关于为什么空白会影响 ruby​​ 函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆