def hoge(array)
res = [ ]
array.each do | data |
value = data.fuga
res<<value
end
res
end
I end up doing this, but I don't think the second, fifth, and seventh lines are ruby-like.
The scene where you can use a map is more refreshing, but how do you write it when you don't?
ruby
For scenes where map
cannot be used, you can write array.inject([]){|r,d|r+[d.fuga]}
.(In this case, you can simply write array.map(&:fuga)
.)
If inject
or map
gets complicated, it may be better to write it with a muddy smell.
How about writing like this?
def hoge(array)
array.map do | data |
data.fuga
end
end
For your information, I have written a code that converts an array of strings into a numeric array with a similar sample code.
def hoge(array)
array.map do | data |
data.to_i
end
end
array=%w (1 2 3 4 5)
phoge(array)
# =>[1, 2, 3, 4, 5]
It's almost the same as the answer above, but I write like this↓
def hoge(array)
array.inject([])do|r,d|
r+=d.fuga
end
end
def hoge(array)
array.map {|data|data.fuga}
end
© 2024 OneMinuteCode. All rights reserved.