"在Ruby中,有不止一种方法可以做同样的事情" - 这是什么意思?

naw*_*fal 3 ruby syntax programming-languages timtowtdi

如果讨论或非常明显,请随意删除此主题.我来自C#背景,我打算学习Ruby.我读到的所有内容似乎都很有趣.但我对Ruby的这个基本哲学感到困惑,"有一种方法可以做一件事".有人可以提供2或3个简单的算术或字符串示例来明确这一点,例如它的语法或逻辑等.

谢谢

slh*_*hck 7

"不止一种做事方式"意味着可以选择以你想要的方式做某事.这样你就可以使用各种编程风格,无论你来自哪个背景.


使用forvs.块进行迭代

你可以迭代一堆这样的东西.这是非常基本的,如果你来自Java背景,这感觉很自然.

for something in an_array
   print something
end
Run Code Online (Sandbox Code Playgroud)

类似Ruby的方式如下:

an_array.each do |something|
    print something
end
Run Code Online (Sandbox Code Playgroud)

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

an_array.each_with_index do |something, index|
    print "At #{index}, there is #{something}"
end
Run Code Online (Sandbox Code Playgroud)

你可以这样做,但现在你看到上面的一个看起来更容易:

index = 0
for something in an_array
    print "At #{index}, there is #{something}"
    index += 1
end
Run Code Online (Sandbox Code Playgroud)

像往常一样传递参数或使用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"
Run Code Online (Sandbox Code Playgroud)

但是,您也可以使用Hash来执行此操作:

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"
Run Code Online (Sandbox Code Playgroud)

第二种形式是Ruby on Rails过度使用的形式.好的是你现在有了命名参数.当你传递它们时,你会更容易记住它们的用途.


Cee*_*man 5

这意味着许多混乱风格之争和由于细微差异而导致的错误,所有这些都以选择自由的名义。