I have been reading a lot about Ruby the past few days. Every SO post I come across I hear that ruby is an elegant language. Can you guys give an example of why ruby is elegan开发者_如何学Pythont compared another language?
It's considered elegant because it's orthogonal. That's a fancy way of saying that similar operations apply to similar operands.
Simple example: +
on integers adds them; on floating point numbers, ditto. On big integers, too. On strings, it concatenates them (which you'd kind of expect too). Now this is not a big deal for +
, you kind of expect it from any decent programming language. But there are operations like map
or filter
, they work on lists (they should!) but they also work on arrays and in fact on anything that can be enumerated or iterated through.
I like how array (or list) indexing works, you can use positive integer indexes to index from the start, or negative indexes to specify a position back from the end of the structure, you can specify a range to pull out a subset... this works for lists, arrays and (sub)strings too. It works on the right side of an assignment (=
), it works on the left side too (you can assign to a substring, thus replacing part of a string). So you don't need a substring_replace
function, you just leverage an existing, general concept.
The author of Ruby expressed this in terms of satisfying the user's (i.e. the programmer's) expectations: There should be as few surprises as possible, whenever common sense would lead you to expect that something works in a certain way, it simply should. He worked very hard to satisfy this requirement. Also, while Ruby borrows a little bit from Perl, the author disagrees with Perl's TMTOWTDI principle in favor of the Zen of Python: "There should be one –and preferably only one– obvious way to do it."
It's also nice that Ruby does closures (= code blocks) so you can specify a function simply by wrapping it in a pair of braces. There are places where it's appropriate to specify a function inline, and Ruby lets you do it conveniently.
Ruby lets you do things with a small amount of coding because its constructs fit together in powerful ways. I dabble in Project Euler and I find that often the shortest legible and understandable solutions were done in Ruby. The very shortest are in J, but that's an APL dialect and to the uninitiated it looks like line noise.
My personal experience bears this out: I taught myself Ruby and Rails and wrote a Web application with medium-complex data analysis in one week. Every principle I learned, I could apply in different places with different data – It Just Works™!
- having open classes i.e. you can add methods to classes after they're defined
- having method_missing i.e. the possibility of handling cases where you're send a message you haven't defined a method for. Again this allows you to write code that adapts rather than just crashing.
- having a Smalltalk-like, consistent OO model e.g. you can do things like 1.class 1.times {}. This makes a lot of the DSL support possible.
- it has blocks/closures - makes it a lot easier to write flexible code
- it doesn't waste your time with static typing of each variable (i.e. trying to solve problems that aren't important if you do TDD)
- You don't have to use class-based OO i.e. it supports prototype-based OO programming
In my experience blocks are the biggest contributing factor to making Ruby elegant. what's more elegant than writing each to iterate over arrays/hashes/etc...
arr = ["one", "two", "three"]
arr.each { |e|
puts e
}
However I believe it's more than this, the elegance of the Ruby language also comes from the libraries. Most libraries have kept to using the unique Ruby 'style' for function names, such as 'each' for iteration or the usage of '!' and '?' at the end of function names for destructive/boolean returning functions, this is what really keeps Ruby 'elegant'.
Ruby and DSLs has been discussed a lot.
Example from sinatra:
get '/' do
'Hello world!'
end
Or from this blog:
ChessGame.new do |move|
move.black_pawn(forward)
move.white_pawn(forward)
#…
move.white_queen(pwn_king)
end
Ruby is all about productivity and programming fun, however there are several reasons why Ruby is elegant:
- Pure OOP: Everything is an object, so you don't have to distinguish between primitive and object types.
- It supports both Functional and Imperative programming paradigms: that leads to both concise and readable code.
- It supports the Principle of Least Surprise: which supports readability.
- It has closures and blocks: which is really cool for doing Internal DSLs.
- It has a robust Metaprogramming API: which empowers writing Internal DSLs as well.
- It's very good at scripting tasks: handling text and xml files and doing administration related stuff(it's being used widely by system admins now a days).
- It has a very cool and supportive community: you will find support and help whatever your problem is. This community supports modern and fashional coding techniques as well like TDD and BDD.
The sum of all the above is that using Ruby you can have:
- Concise code: Compared to Java and C++, at least you can save yourself 50% of code typing.
- Readablility.
Thus having readable and concise code -> less code to write -> less code to test and maintain -> Productivity.
I shouldn't forget to mention the great supportive community behind Ruby.
I may not be able to argue that it's elegant, I think that in general elegance is derived by the programmer's implementation. However I can argue that it is concise and I think that's what a lot of people are really feeling when they say that Ruby is elegant. Often times code that comes together quickly feels elegant.
You can see the results of the programming language shootout here. You'll notice that Ruby 1.9 is smacked flat against the left side meaning it's super concise. I would wager that anyone talking about a language being elegant is talking about a language that is either on the left side or close. Haskell being one of the only notable exceptions I know which takes a lot of effort to get certain things done but still feels exceedingly elegant doing it.
everthing is an object (ps. like in smalltalk ..):
3.times { p "olleh" }
extensible/open classes (e.g. from Rails):
10.days_ago
.. and more on ruby elegance: http://www.benhughes.name/files/presentations/ruby_elegance.pdf
Just an amusing side note: this feels like php yet is Ruby (from earlier today), but the first answer feels like elegant Ruby. In PHP I ended up writing stupid long code like the linked post to do little things. In part because lambdas are basically nonexistent. So I would have to say that Ruby's lambda support together with map/reduce is what makes it elegant to me.
精彩评论