gpt4 book ai didi

ruby - "In Ruby there' 做同一件事的方式不止一种”——这是什么意思?

转载 作者:数据小太阳 更新时间:2023-10-29 07:44:29 24 4
gpt4 key购买 nike

如果讨论过或非常明显,请随时删除该主题。我来自 C# 背景,我打算学习 Ruby。我读到的一切似乎都很有趣。但是我对 Ruby 的这种基本哲学感到困惑,即“做一件事的方法不止一种”。有人可以提供 2 或 3 个简单的算术或字符串示例来阐明这一点,比如关于语法或逻辑等。

谢谢

最佳答案

“不止一种做某事的方式”意味着可以选择按照您想要的方式做某事。这样,无论您的背景如何,您都可以使用各种编程风格。


使用 for 与 block 的迭代

您可以像这样遍历数组。这是非常基础的,如果您有 Java 背景,这感觉很自然。

for something in an_array
print something
end

更像 Ruby 的方式如下:

an_array.each do |something|
print something
end

第一种是众所周知的做事方式。第二个是使用 blocks ,一个非常强大的概念,您会在许多 Ruby 习语中找到它。基本上,数组知道如何遍历其内容,因此您可以修改它并添加如下内容:

an_array.each_with_index do |something, index|
print "At #{index}, there is #{something}"
end

你也可以这样做,但现在你看到上面的看起来更简单了:

index = 0
for something in an_array
print "At #{index}, there is #{something}"
index += 1
end

照常传递参数或使用Hashes

通常,您会像这样传递参数:

def foo(arg1, arg2, arg3)
print "I have three arguments, which are #{arg1}, #{arg2} and #{arg3}"
end

foo("very", "easy", "classic")

=> "I have three arguments, which are very easy and classic"

但是,您也可以使用哈希来做到这一点:

def foo(args)
print "I have multiple arguments, they are #{args[:arg1]}, #{args[:arg2]} and #{args[:arg3]}"
end

foo :arg1 => "in a", :arg2 => "hash", :arg3 => "cool"

=> "I have three arguments, which are in a hash and cool"

第二种形式被 Ruby on Rails 过度使用。好消息是您现在有了命名参数。当您经过它们时,您会更容易记住它们的用途。

关于ruby - "In Ruby there' 做同一件事的方式不止一种”——这是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6401361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com