【问题标题】:How to only print the first value in the row from a CSV file in Ruby?如何仅从 Ruby 中的 CSV 文件打印行中的第一个值?
【发布时间】:2019-09-26 02:56:56
【问题描述】:

我有一个 excel 表(.csv 文件),其中包含不同交通摄像头位置的 lats 和 longs,并且我构建了一个使用 haversinegeocoder gem 的 Ruby 程序来查找用户输入的地址与 CSV 文件中不同摄像头位置之间的距离,然后打印出离用户提供的地址最近的摄像头。

我的问题是,它打印出最近的摄像头的整行信息,我希望它只打印出行中的第一个值(最近的交通摄像头位置的交点)。

CSV 文件与此类似:


位置                              纬度       经度  运营

圣。查尔斯@华盛顿大街 29.93102 -90.086 是的

所以我的问题是,为了简化,我如何让它打印出来:

St. Charles @ Washington Ave. is 1.0351466822038633 miles away!

代替:

St. Charles @ Washington Ave.,30.015934,-90.075197,Y is 1.0351466822038633 miles away!

我不希望它打印出额外的值,例如 latlong 和运行状态 (Y),只是摄像头交叉点的名称。

这是代码的 sn-p(不要给出我的太多代码,以防其他学生将来收到相同的作业并需要自己弄清楚):

require 'csv'
require 'haversine'
require 'geocoder'


# ***missing code that does all of the work converting the distance between the given address 
# and the addresses in the .CSV file and finds the closest traffic camera***

min_num = distance #in miles, calculated by Haversine and Geocoder

# reads the line of the CSV file with the shortest distance to the input address and assigns value to the variable 'closest_cam'

closest_cam = CSV.readlines("./cameras.csv", headers: true)[index_num]

# prints the closest camera to the given address and how far away it is (in miles), 
# the problem is that it prints the entire row, with lats, longs, etc. instead of just the name of the closest camera intersection.. ):<        

puts "#{closest_cam} is #{min_num} miles away!"

【问题讨论】:

    标签: ruby csv readline readlines


    【解决方案1】:

    puts #{closest_cam[0]} is #{min_num} miles away! 最近的_cam 变量是行(数组),每列是该数组中的一个位置。

    从 CSV 模块中读出(实际上与 readlines 相同): https://ruby-doc.org/stdlib-2.6.1/libdoc/csv/rdoc/CSV.html#method-i-readlines

    删除剩余的行并返回一个数组数组。

    所以你需要做的就是调用行数组中的第一列: #{closest_cam[0]},你可以用 1,2 等来调用其他列。

    编辑: 我会小心,但如果你有一个包含更多行的 csv,真正的答案是 closest_cam 实际上是整个 csv 作为一个数组,每一行作为该数组中的一个位置作为一个数组本身。

    所以答案是closest_cam[0][0] 第一个 [0] 获取 csv 数组中的第一行,第二个 [0] 获取第一行的第一列。

    【讨论】:

    • closest_cam[0][0] 只是返回了名称的第一个字母,但最接近的cam[0] 返回了行中第一个条目的全名。非常感谢!
    • @VictoriaGraves 如果它解决了您的问题,请确保接受答案
    • 很高兴它有帮助!正如Виктор 所说,请接受答案,因为它让社区知道您得到了正确的答案。 :)
    猜你喜欢
    • 2017-04-24
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2015-01-23
    • 1970-01-01
    相关资源
    最近更新 更多