Ruby 我怎样才能提高?
我想知道是否有人能指出一种更干净更好的方法来编写粘贴在这里的代码。代码从yelp中提取一些数据,并将其处理为json格式。我不使用hash.to_json的原因是它抛出了某种堆栈错误,我只能假设这是由于hash太大(不是特别大)Ruby 我怎样才能提高?,ruby,Ruby,我想知道是否有人能指出一种更干净更好的方法来编写粘贴在这里的代码。代码从yelp中提取一些数据,并将其处理为json格式。我不使用hash.to_json的原因是它抛出了某种堆栈错误,我只能假设这是由于hash太大(不是特别大) 响应对象=散列 text=保存到文件的输出 无论如何,我很感激你的指导 def mineLocation client = Yelp::Client.new request = Yelp::Review::Request::GeoPoint.new(:la
- 响应对象=散列
- text=保存到文件的输出
def mineLocation
client = Yelp::Client.new
request = Yelp::Review::Request::GeoPoint.new(:latitude=>13.3125,:longitude => -6.2468,:yws_id => 'nicetry')
response = client.search(request)
response['businesses'].length.times do |businessEntry|
text =""
response['businesses'][businessEntry].each { |key, value|
if value.class == Array
value.length.times { |arrayEntry|
text+= "\"#{key}\":["
value[arrayEntry].each { |arrayKey,arrayValue|
text+= "{\"#{arrayKey}\":\"#{arrayValue}\"},"
}
text+="]"
}
else
text+="\"#{arrayKey}\":\"#{arrayValue}\","
end
}
end
end
我想看看您从hash.to_json中得到的错误,看看是否能找到原因 就您的Ruby代码而言,有几点值得注意:
- 使用
do。。是一个 当你可以使用.length.times
例如。每个
response['business'],每个都是
- 在您的
案例中else
它看起来像text+=“\”{arrayKey}\”:\“{arrayValue}\”,“
和arrayKey
超出范围,因为 它们仅用作块 上述arrayValue
中的变量
将文本设置回空 在外部对象的每次迭代中使用字符串 看起来就像代码一样 就像由 循环的先前迭代是 丢弃text=”“
- 使用
do。。是一个 当你可以使用.length.times
例如。每个
response['business'],每个都是
- 在您的
案例中else
它看起来像text+=“\”{arrayKey}\”:\“{arrayValue}\”,“
和arrayKey
超出范围,因为 它们仅用作块 上述arrayValue
中的变量
将文本设置回空 在外部对象的每次迭代中使用字符串 看起来就像代码一样 就像由 循环的先前迭代是 丢弃text=”“
require 'json'
def mine_location
client = Yelp::Client.new
request = Yelp::Review::Request::GeoPoint.new(latitude: 13.3125,
longitude: -6.2468, yws_id: 'nicetry')
response = client.search(request)
return response['businesses'].to_json
end
这对我来说很好
如果出于任何原因,您真的必须编写自己的JSON发射器实现,那么这里有几个提示供您参考
在代码中完全忽略的第一件事是Ruby是一种面向对象的语言,更具体地说是一种基于类的面向对象语言。这意味着通过构建一个对象网络来解决问题,这些对象通过消息传递相互通信,并通过执行这些对象所属的类中定义的方法来响应这些消息
这给了我们很多功能:动态调度、多态性、封装和其他许多功能。利用这些,您的JSON发射器将如下所示:
class Object
def to_json; to_s end
end
class NilClass
def to_json; 'null' end
end
class String
def to_json; %Q'"#{to_s}"' end
end
class Array
def to_json; "[#{map(&:to_json).join(', ')}]" end
end
class Hash
def to_json; "{#{map {|k, v| "#{k.to_json}: #{v.to_json}" }.join(', ')}}" end
end
class Object
def to_json(*) to_s end
end
class String
def to_json(*) inspect end
end
class Array
def to_json(indent=0)
"[\n#{' ' * indent+=1}#{
map {|el| el.to_json(indent) }.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}]"
end
end
class Hash
def to_json(indent=0)
"{\n#{' ' * indent+=1}#{
map {|k, v|
"#{k.to_json(indent)}: #{v.to_json(indent)}"
}.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}}"
end
end
mine\u location
看起来与上面一样,只是明显没有require'json'
部分
如果希望JSON格式良好,可以尝试以下方法:
class Object
def to_json; to_s end
end
class NilClass
def to_json; 'null' end
end
class String
def to_json; %Q'"#{to_s}"' end
end
class Array
def to_json; "[#{map(&:to_json).join(', ')}]" end
end
class Hash
def to_json; "{#{map {|k, v| "#{k.to_json}: #{v.to_json}" }.join(', ')}}" end
end
class Object
def to_json(*) to_s end
end
class String
def to_json(*) inspect end
end
class Array
def to_json(indent=0)
"[\n#{' ' * indent+=1}#{
map {|el| el.to_json(indent) }.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}]"
end
end
class Hash
def to_json(indent=0)
"{\n#{' ' * indent+=1}#{
map {|k, v|
"#{k.to_json(indent)}: #{v.to_json(indent)}"
}.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}}"
end
end
这段代码中实际上没有Ruby特有的东西。这正是该解决方案在任何其他基于类的面向对象语言(例如Java)中的外观。这只是面向对象的设计101
唯一特定于语言的是如何“修改”类并向它们添加方法。在Ruby或Python中,您实际上只是修改类。在C#和visualbasic.NET中,可能会使用扩展方法,在Scala中可能会使用隐式转换,在Java中可能会使用Decorator设计模式
代码的另一个大问题是,您试图解决一个显然是递归的问题,而实际上从未递归过。这就是行不通。您编写的代码基本上是Fortran-57代码:没有对象和递归的过程。即使只是从Fortran向Pascal迈进一步,也能为您提供一个很好的递归过程解决方案:
def jsonify(o)
case o
when Hash
"{#{o.map {|k, v| "#{jsonify(k)}: #{jsonify(v)}" }.join(', ')}}"
when Array
"[#{o.map(&method(:jsonify)).join(', ')}]"
when String
o.inspect
when nil
'null'
else
o.to_s
end
end
当然,您可以在此处使用缩进玩相同的游戏:
def jsonify(o, indent=0)
case o
when Hash
"{\n#{' ' * indent+=1}#{
o.map {|k, v|
"#{jsonify(k, indent)}: #{jsonify(v, indent)}"
}.join(", \n#{' ' * indent}") }\n#{' ' * indent-=1}}"
when Array
"[\n#{' ' * indent+=1}#{
o.map {|el| jsonify(el, indent) }.join(", \n#{' ' * indent}") }\n#{' ' * indent-=1}]"
when String
o.inspect
when nil
'null'
else
o.to_s
end
end
这是put mine\u location
的缩进输出,使用第二个(缩进)版本的to\u json
或第二个版本的jsonify
生成,这并不重要,它们都有相同的输出:
[
{
"name": "Nickies",
"mobile_url": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ",
"city": "San Francisco",
"address1": "466 Haight St",
"zip": "94117",
"latitude": 37.772201,
"avg_rating": 4.0,
"address2": "",
"country_code": "US",
"country": "USA",
"address3": "",
"photo_url_small": "http://static.px.yelp.com/bpthumb/mPNTiQm5HVqLLcUi8XrDiA/ss",
"url": "http://yelp.com/biz/nickies-san-francisco",
"photo_url": "http://static.px.yelp.com/bpthumb/mPNTiQm5HVqLLcUi8XrDiA/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_4.png",
"is_closed": false,
"id": "yyqwqfgn1ZmbQYNbl7s5sQ",
"nearby_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA",
"state_code": "CA",
"reviews": [
{
"rating": 3,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/ZQDXkIwQmgfAcazw8OgK2g/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:t-sisM24K9GvvYhr-9w1EQ",
"user_url": "http://yelp.com/user_details?userid=XMeRHjiLhA9cv3BsSOazCA",
"user_photo_url": "http://static.px.yelp.com/upthumb/ZQDXkIwQmgfAcazw8OgK2g/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_3.png",
"id": "t-sisM24K9GvvYhr-9w1EQ",
"text_excerpt": "So I know gentrification is supposed to be a bad word and all (especially here in SF), but the Lower Haight might benefit a bit from it. At least, I like...",
"user_name": "Trey F.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=t-sisM24K9GvvYhr-9w1EQ",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_3.png"
},
{
"rating": 4,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/Ghwoq23_alkaXawgqj7dBA/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:8xTNOC9L5ZXwGCMNYY-pdQ",
"user_url": "http://yelp.com/user_details?userid=4F2QG3adYIUNXplqqp9ylA",
"user_photo_url": "http://static.px.yelp.com/upthumb/Ghwoq23_alkaXawgqj7dBA/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_4.png",
"id": "8xTNOC9L5ZXwGCMNYY-pdQ",
"text_excerpt": "This place was definitely a great place to chill. The atmosphere is very non-threatening and very neighborly. I thought it was cool that they had a girl dj...",
"user_name": "Jessy M.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=8xTNOC9L5ZXwGCMNYY-pdQ",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_4.png"
},
{
"rating": 5,
"user_photo_url_small": "http://static.px.yelp.com/upthumb/q0POOE3vv2LzNg1qN8MMyw/ss",
"url": "http://yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ#hrid:pp33WfN_FoKlQKJ-38j_Ag",
"user_url": "http://yelp.com/user_details?userid=FmcKafW272uSWXbUF2rslA",
"user_photo_url": "http://static.px.yelp.com/upthumb/q0POOE3vv2LzNg1qN8MMyw/ms",
"rating_img_url_small": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_small_5.png",
"id": "pp33WfN_FoKlQKJ-38j_Ag",
"text_excerpt": "Love this place! I've been here twice now and each time has been a great experience. The bartender is so nice. When we had questions about the drinks he...",
"user_name": "Scott M.",
"mobile_uri": "http://mobile.yelp.com/biz/yyqwqfgn1ZmbQYNbl7s5sQ?srid=pp33WfN_FoKlQKJ-38j_Ag",
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_5.png"
}
],
"phone": "4152550300",
"neighborhoods": [
{
"name": "Hayes Valley",
"url": "http://yelp.com/search?find_loc=Hayes+Valley%2C+San+Francisco%2C+CA"
}
],
"rating_img_url": "http://static.px.yelp.com/static/20070816/i/ico/stars/stars_4.png",
"longitude": -122.429926,
"categories": [
{
"name": "Dance Clubs",
"category_filter": "danceclubs",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=danceclubs"
},
{
"name": "Lounges",
"category_filter": "lounges",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=lounges"
},
{
"name": "American (Traditional)",
"category_filter": "tradamerican",
"search_url": "http://yelp.com/search?find_loc=466+Haight+St%2C+San+Francisco%2C+CA&cflt=tradamerican"
}
],
"state": "CA",
"review_count": 32,
"distance": 1.87804019451141
}
]
看起来您的代码最终要做的是:
require 'json'
def mine_location
client = Yelp::Client.new
request = Yelp::Review::Request::GeoPoint.new(latitude: 13.3125,
longitude: -6.2468, yws_id: 'nicetry')
response = client.search(request)
return response['businesses'].to_json
end
这对我来说很好
如果出于任何原因,您真的必须编写自己的JSON发射器实现,那么这里有几个提示供您参考
在代码中完全忽略的第一件事是Ruby是一种面向对象的语言,更具体地说是一种基于类的面向对象语言。这意味着通过构建一个对象网络来解决问题,这些对象通过消息传递相互通信,并通过执行这些对象所属的类中定义的方法来响应这些消息
这给了我们很多功能:动态调度、多态性、封装和其他许多功能。利用这些,您的JSON发射器将如下所示:
class Object
def to_json; to_s end
end
class NilClass
def to_json; 'null' end
end
class String
def to_json; %Q'"#{to_s}"' end
end
class Array
def to_json; "[#{map(&:to_json).join(', ')}]" end
end
class Hash
def to_json; "{#{map {|k, v| "#{k.to_json}: #{v.to_json}" }.join(', ')}}" end
end
class Object
def to_json(*) to_s end
end
class String
def to_json(*) inspect end
end
class Array
def to_json(indent=0)
"[\n#{' ' * indent+=1}#{
map {|el| el.to_json(indent) }.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}]"
end
end
class Hash
def to_json(indent=0)
"{\n#{' ' * indent+=1}#{
map {|k, v|
"#{k.to_json(indent)}: #{v.to_json(indent)}"
}.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}}"
end
end
mine\u location
看起来与上面一样,只是明显没有require'json'
部分
如果希望JSON格式良好,可以尝试以下方法:
class Object
def to_json; to_s end
end
class NilClass
def to_json; 'null' end
end
class String
def to_json; %Q'"#{to_s}"' end
end
class Array
def to_json; "[#{map(&:to_json).join(', ')}]" end
end
class Hash
def to_json; "{#{map {|k, v| "#{k.to_json}: #{v.to_json}" }.join(', ')}}" end
end
class Object
def to_json(*) to_s end
end
class String
def to_json(*) inspect end
end
class Array
def to_json(indent=0)
"[\n#{' ' * indent+=1}#{
map {|el| el.to_json(indent) }.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}]"
end
end
class Hash
def to_json(indent=0)
"{\n#{' ' * indent+=1}#{
map {|k, v|
"#{k.to_json(indent)}: #{v.to_json(indent)}"
}.join(", \n#{' ' * indent}")
}\n#{' ' * indent-=1}}"
end
end
这段代码中实际上没有Ruby特有的东西。这正是该解决方案在任何其他基于类的面向对象语言(例如Java)中的外观。这只是面向对象的设计101
唯一特定于语言的是如何“修改”类并向它们添加方法。在Ruby或Python中,您实际上只是修改类。在C#和visualbasic.NET中,可能会使用扩展方法,在Scala中可能会使用隐式转换,在Java中可能会使用Decorator设计模式