这个字符串可以正确拆分吗?

时间:2014-02-09 01:08:00

标签: ruby-on-rails ruby loops split

我正在使用Rails,并拥有此种子数据:

majors = 'business/marketing: 15%|social sciences: 14%|health professions: 11%|english: 10%|engineering: 9%|psychology: 8%|biology: 7%|history: 5%'

在我的视图文件中,我可以访问@college.majors,然后将其拆分为|,并将其打印出来。但是,我正在尝试使用Google Charts将其变成条形图。它需要格式化如下:

var popular_majors = google.visualization.arrayToDataTable([
          ['Major', 'Percentage'],
          ['Psychology',  20],
          ['Business',  15],
          ['Engineering',  12],
          ['Biology',  11],
          ['Economics',  8],
          ['History',  6],
          ['Mathematics',  5]
        ]);

是否有可能正确地拆分字符串,然后以这样的方式遍历它,我可以打印出奇数成员作为主要成员,偶数成员作为百分比打印出来?

代码:

var popular_majors = google.visualization.arrayToDataTable(<%= @college.majors.gsub('%', '').split('|').map{ |element| element.split(': ') }.unshift(['Major', 'Percentage']).to_s.html_safe %>)
            var popular_majors_options = {
              title: 'Most Popular Majors',
              legend: 'none',
              hAxis: {title: 'Percentage'}
            };
            var chart = new google.visualization.BarChart(document.getElementById('popular_majors_chart'));
            chart.draw(popular_majors, popular_majors_options);

            var ethnicities = google.visualization.arrayToDataTable(<%= @college.ethnicity.gsub('%', '').split('|').map{ |element| element.split(': ') }.unshift(['Ethnicity', 'Percentage']).to_s.html_safe %>)
            var ethnicities_options = {
              title: 'Ethnicities',
              legend: 'none',
              hAxis: {title: 'Percentage'}
            };
            var chart = new google.visualization.BarChart(document.getElementById('ethnicities_chart'));
            chart.draw(ethnicities, ethnicities_options);

3 个答案:

答案 0 :(得分:1)

这样的事情:

content = "business/marketing: 15%|social sciences: 14%|health professions: 11%|english: 10%|engineering: 9%|psychology: 8%|biology: 7%|history: 5%"
content.split('|').map{ |element| result = element.split(': '); [result[0], result[1].to_i] }.unshift(['Major', 'Percentage'])
# => [["Major", "Percentage"], ["business/marketing", 15], ["social sciences", 14], ["health professions", 11], ["english", 10], ["engineering", 9], ["psychology", 8], ["biology", 7], ["history", 5]]

我错过了在您的视图中使用JavaScript的观点。您可以通过在结果数组上调用to_s来执行此操作:

var popular_majors = google.visualization.arrayToDataTable(<%= @college.majors.split('|').map{ |element| result = element.split(': '); [result[0], result[1].to_i] }.unshift(['Major', 'Percentage']).to_s.html_safe %>)

答案 1 :(得分:0)

split一次在管道上,然后再在空间上。

答案 2 :(得分:0)

require 'json'

majors.split('|').collect {|major| major.gsub('%', '').split(':').collect(&:strip) }.unshift(['Major', 'Percentage']).to_json

你可以做一些其他技巧,比如拆分'%|'和':'以避免gsub和strip,但对我来说,它似乎有点脆弱。格式的细微变化会破坏它。