From: Lloyd Linklater Date: 2008-10-22T23:14:27+09:00 Subject: Re: What exactly does "rubyish" or "ruby way" mean? Nit Khair wrote: > Over the last month I have been reading a lot of blogs, searching, going > through source code of some apps and my pickaxe. I am still unable to > clearly understand what all "the ruby way" means. > > I will be perfectly happy if you can tell me: > > 1. phrases to google on, or check in pickaxe > 2. pointers to specific libraries or classes i can study > 3. link to any article I may have missed, or blog > > The only thing I can put down, that i have gleaned, is the usage of > procs/blocks, i.e. allowing the user to pass in blocks/yielding a value > or self. I liked the chapter on Ruby Tk in pickaxe (since I am hoping to > write a rubyish wrapper to ncurses). > > Surely there is more to the ruby way than blocks/procs/lambda. Would > really appreciate pointers. > > thanks. In short, I believe that a program is "rubyish" when it is the language solving the problem rather than the writing of an algorithm to do it, as in Java et. al. Here are possible examples from recent threads here. Consider how this would be written in java, then compare it to these. First example: 1. You are given a big (odd) string with words separated by a space: "eggs lovely spam spam bar bar bar bar bar baz baz baz baz baz baz eggs bar baz baz baz baz baz eggs spam spam" 2. You want to make a list of all the different words and how many times each one occurs, then display the alphabetized list. Just think how you would do that in an algorithm based language like java. That is a LOT of work. Now look at a ruby way: s = "eggs lovely spam spam bar bar bar bar bar baz baz baz baz baz baz eggs bar baz baz baz baz baz eggs spam spam".split(/[ ]/) p s.inject(Hash.new(0)) {|h, e| h[e] += 1; h}.sort Second example: You are given an array of numbers as strings: ["10.1", "7.4", "10.9", "10.11", "10.10"] If you do a standard sort, it turns into: ["10.1", "10.10", "10.11", "10.9", "7.4"] What you want is a numeric sort: ["7.4", "10.1", "10.9", "10.10","10.11"] Extra credit if the sort allows for the addition of numeric bits. E.g. ["10.1.5", "7.4.4", "10.9.3", "10.11.2", "10.10.3", "10.10.1"] Ruby solution: arr = ["10.1.5", "7.4.4", "10.9.3", "10.11.2", "10.10.3", "10.10.1"] p arr.sort_by { |str| str.split('.').map { |x| x.to_i } } => ["7.4.4", "10.1.5", "10.9.3", "10.10.1", "10.10.3", "10.11.2"] -- Posted via http://www.ruby-forum.com/.