Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a clean way of defining an array of strings in Ruby?

Let's say for whatever reason, I am going to define an array variable in a ruby script file that holds all the US states as strings. What is a clean way of doing this? And by clean, I'm not really looking for performance, but more readability.

Here are a couple ways I have tried, but don't really like:

A single LONG line definition. I don't care for this because it is very long, or needs to be word wrapped.

states = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado", ...]

Another options would be a multiple line definition, pushing strings to the array. This resolves the long lines (width-wise), but I don't care for the mixed use of assignment and array.push.

states = ["Alabama", "Alaska", "Arizona"]
states.push("Arkansas", "California", "Colorado")
states.push("...")

Yet another option would be single line pushes. This seems consistent, but could be quite long to accomplish.

states = []
states.push("Alabama")
states.push("Alaska")
states.push("Arizona")
states.push("...")

Now, sure, ideally, I would not be hard-coding my array values and should be pulling them from a database or web service, etc. But, for the purpose of the question, let's assume that the values do not exist anywhere else currently.

like image 996
Ryan Miller Avatar asked Dec 05 '22 20:12

Ryan Miller


1 Answers

There's an actual syntax element in ruby for defining such arrays:

> states = %w(Alabama Alaska Arizona
>    Arkansas California
>    Colorado)
=> ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado"]

Note though, that it will split the elements on whitespace. So an entry like "North Dakota" will end up as two items: "North" and "Dakota".

like image 139
Holger Just Avatar answered May 18 '23 18:05

Holger Just