开发者

Ruby: How to iterate over a hash and do something different based on the number of items?

开发者 https://www.devze.com 2023-03-26 02:44 出处:网络
I am working with a hash that looks something like this: h = { \"side1\"=>[开发者_JAVA百科\"green\", \"Green\"],

I am working with a hash that looks something like this:

h = {
    "side1"=>[开发者_JAVA百科"green", "Green"], 
    "side2"=>["verde", "Verde"]
}

However, it may only have one item in it:

h = { 
    "side2"=>["verde", "Verde"]
}

I would like to output the hash so that it looks something like this:

User changed side1 from green to Green and side2 from verde to Verde

When there are two items will be separated from an "and". Otherwise it will look like this:

User changed side2 from verde to Verde

This is all happening in my rails view script. How can I write the code to be able to do this?


You could do something like this:

h = {
    "side1"=>["green", "Green"], 
    "side2"=>["verde", "Verde"]
}
h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ')
# "side1 from green to Green and side2 from verde to Verde"

h = { 
    "side2"=>["verde", "Verde"]
}
h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ')
# side2 from verde to Verde"

So, in an ERB view:

User changed <%= h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.join(' and ') %>.

If you were doing this sort of thing a lot then you might want to build a helper for it.

You could also use to_sentence since you're in Rails:

User changed <%= h.map { |k,v| "#{k} from #{v[0]} to #{v[1]}" }.to_sentence %>.

The to_sentence approach also scales up to more than two elements better. So, if you also had "side3"=>["pancakes", "Pancakes"], then you'd get:

User changed side1 from green to Green, side2 from verde to Verde, and side3 from pancakes  to Pancakes.


Here's a possible solution:

hash = {
    "side1"=>["green", "Green"], 
    "side2"=>["verde", "Verde"]
}

result = hash.map do |key,value|
  "#{key} from #{value.first} to #{value.last}"
end

puts "User changed #{result.to_sentence}"

The output is going to be :

User changed side1 from green to Green and side2 from verde to Verde

While if you added one item only:

User changed side1 from green to Green
0

精彩评论

暂无评论...
验证码 换一张
取 消