code to be added to an array for return values

Asked 2 years ago, Updated 2 years ago, 79 views

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

2022-09-30 21:11

4 Answers

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.


2022-09-30 21:11

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]


2022-09-30 21:11

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


2022-09-30 21:11

def hoge(array)
  array.map {|data|data.fuga}
end


2022-09-30 21:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.