2011-05-30 110 views
1

http://www.pythonchallenge.com/pc/def/linkedlist.php是否有比下面的红宝石代码更好的/可选的/更易读的解决方案? 我能理解它,但它只是似乎并没有我很清楚...pythonchallenge.com 4在红宝石溶液

#!/usr/bin/env ruby -w 
# encoding: utf-8 

require 'net/http' 

Net::HTTP.start 'www.pythonchallenge.com' do |http| 
    nothing = 12345 

    nothing = case http.get("/pc/def/linkedlist.php?nothing=#{nothing}").body 
    when /(\d+)$/ then $1.to_i 
    when /by two/ then nothing/2 
    when /\.html/ then puts $` 
    end while nothing 
end 

回答

3

这是好的,但是让我们试着让它多一点可读性:

#!/usr/bin/env ruby -w 
# encoding: utf-8 

require 'net/http' 

Net::HTTP.start 'www.pythonchallenge.com' do |http| 
    next_one = 12345 

    while next_one 
    response = http.get("/pc/def/linkedlist.php?nothing=#{next_one}").body 

    case response 
     when /Divide by two and keep going./ then 
     next_one = next_one/2 
     when /and the next nothing is (\d+)/ then 
     next_one = $1.to_i 
     else 
     puts "Solution url: www.pythonchallenge.com/pc/def/linkedlist.php?nothing=#{next_one}" 
     next_one = false 
    end 
    end 

end 
+0

我得到以下“

”块中出现错误:“92118”的未定义方法'/':字符串(NoMethodError) \t from /Users/batman/.rvm/rubies/ruby-1.9.2-p180/lib/ruby /1.9.1/net/http.rb:627:in'start' \t from /Users/batman/.rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/net/http。 rb:490:在'开始' \t from 7.rb:3:in'
'“ – 2011-05-30 23:54:28

+0

@raphael_turtle:好的,在'next_one = $ 1.to_i'上加了'to_i'。 (我正在尝试从更高的价值)。 – robertodecurnex 2011-05-31 13:11:19