Alexandru E. Ungur wrote: > Hi all, > > I recently recently released my first vim script, nothing big, it > just toggles words between true/false, on/off, etc. You can find > more here http://vim.sourceforge.net/scripts/script.php?script_id=1748 > if you want. > > The thing is, I'm not sure if I chose the most elegant/beautiful/** > way to solve the problem, basically I ended up deciding between > two ways of handling the problem: > > class String > @@pairs = [ %w[on off], %w[yes no], %w[true false] ] > > def toggle_word1 > pair = @@pairs.select{|p| p.include?(downcase)}.flatten > return nil if pair.empty? > antiword = pair[pair.index(downcase) ^ 1] > case self > when upcase then return antiword.upcase > when downcase then return antiword.downcase > when capitalize then return antiword.capitalize > else return antiword > end > end > > def toggle_word2 > pair = @@pairs.select{|p| p.include?(downcase)}.flatten > wordcase = %w[upcase downcase capitalize].detect {|c| send(c) == self} || "downcase" > pair.empty? ? nil : pair[pair.index(downcase) ^ 1].send(wordcase) > end > end > > Both toggle_word1 and toggle_word2 are doing the exact same thing, that is: > "Yes".toggle_word1 # => "No" > "No".toggle_word2 # => "Yes" > and so on. > > My question is, which is more elegant, more... rubyful ? > I like that toggle_word1 is almost like plain english, especially > that "case" construct, but I like in toggle_word2 that the same "case" > construct was replaced with a single line of code, well with two > actually. However perhaps toggle_word2 is a little too much > code golfing...? > > > Thank you in advance for your comments, > Have a nice day everyone, > Alex class String def toggle_word3 words = %w[on off yes no true false] word = words[ i = words.index(downcase) ] anti = words[ i + (i%2>0 ? -1 : 1 ) ] %w( capitalize upcase ).each{|meth| return anti.send(meth) if word.send(meth) == self } anti end end