奇怪的Ruby语法? [英] Strange Ruby Syntax?
问题描述
<$ c我在ruby-lang.org上做了Ruby 20分钟的教程,并且遇到了这个代码搞乱了irb: $ C> IRB(主):015:0> def h(name)
irb(main):016:1>放入Hello#{name}!
irb(main):017:1>结束
根据解释,#{name}
部分只是将该变量添加到字符串?我认为这是一种奇怪而冗长的写作方式,所以我只是认为我会尝试Hello+ name
,它的工作方式完全一样。
我试图找到#{}
的含义,我无法找到任何有关它的内容,所以我想我' d问社区..有什么区别?是否有一个?
感谢您的提前!
+
比较容易,但是在这种情况下,您离开感叹号。考虑:
putsHello#{name}!
vs。
放入Hello+名称+!
我发现第一个更具可读性,尤其是在字符串中多次使用时。 b
$ b
另外考虑在第二个版本的Hello后面留出空间是多么容易:
放入你好+名字+!
很容易编写,但可能不是您的意思。
最后,当您插入的内容不是字符串时,它会产生更大的差异:
得分者是#{姓名},得分为#{分数}!
顺便说一句,搜索字符串插值可能会使搜索更容易,而不仅仅是搜索为语法。
I'm doing the Ruby 20 minute tutorial on ruby-lang.org and I came across this code messing with the irb:
irb(main):015:0> def h(name)
irb(main):016:1> puts "Hello #{name}!"
irb(main):017:1> end
based on the explanation, the #{name}
part is just adding the variable to the string? I thought this was an odd and verbose way of writing it so I just thought I'd try "Hello" + name
and it worked exactly the same way..
I googled around trying to find a meaning to #{}
and I cant find anything talking about it so I thought I'd ask the community.. what is the difference? Is there one?
Thanks in advance!
Sometimes using +
is easier, but in this case you left off the exclamation point. Consider:
puts "Hello #{name}!"
vs.
puts "Hello " + name + "!"
I find the first more readable, especially when used several times in a string.
Also consider how easy it was to leave out the space after "Hello" in the second version:
puts "Hello" + name + "!"
is easy to write, but probably isn't what you mean.
Last, it makes an even bigger difference when what you're interpolating isn't a string:
puts "The Winner was #{name} with a score of #{score}!"
By the way, searching for "string interpolation" will probably make it easier to find things than just searching for the syntax.
这篇关于奇怪的Ruby语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!