String to Array?


#1

I’ve got a string of keywords “internet explorer microsoft windows
browser” - I want to output each word with a link_to a controller I’ve
built that searches based on a keyword.

I managed to split the string, but I don’t know how then to loop over it
to output the link_tos?

matt


Matt Lee
Senior Technical Developer
NHS Connecting for Health



This e-mail is confidential and privileged. If you are not the intended
recipient please accept our apologies; please do not disclose, copy or
distribute information in this e-mail or take any action in reliance on
its
contents: to do so is strictly prohibited and may be unlawful. Please
inform us that this message has gone astray before deleting it. Thank
you
for your co-operation.



#2

Matt Lee wrote:

I’ve got a string of keywords “internet explorer microsoft windows
browser” - I want to output each word with a link_to a controller I’ve
built that searches based on a keyword.

I managed to split the string, but I don’t know how then to loop over it
to output the link_tos?

str.split(’ ‘).collect{|s| link_to(s, foo)}.join(’
’)

The collect (and inject) methods are most useful for this sort of thing.


#3

<% input = “internet explorer microsoft windows browser” %>
<%= input.split.each {|word| link_to word, :controller=>‘controller’,
:action=>‘action’} %>

This should work, but hasn’t been tested

_Kevin


#4

Creating an array out of a bunch of words like that is often done like:

%w{internet explorer microsoft windows browser}

You can assign that to a variable or just build off it:

words = %w{internet explorer microsoft windows browser}
links = words.collect { |w| link_to … }

or

%w{internet explorer microsoft windows browser}.collect …

Then you could either do the .join(’
’) Alex mentioned or something
like:

    <% links.each do |link| -%> <%= "
  • #{link}
  • " %> <% end -%>

Or whatever your needs might be.

This would be where David Black’s new book, Ruby for Rails would come
in handy, or, of course, The Pickaxe.

-Tom