mapping elements of an array differently based on position
I want to map elements of an array such that all elements of the array are floats, except the first element wh开发者_如何学Pythonich is a string.
Anyone know how I can do this?
Tried this but doesn't work:
arr = arr.map { |e| e.to_i if e != arr.first }
Another solution is
[array.first] + array.drop(1).map &:to_f
This makes it clear that you want the first element separate from the rest, and you want the rest of the elements to be of type Float
. Other options include
array.map { |element, index| index == 0 ? element : element.to_f }
array.map { |element| element == array.first ? element : element.to_f }
You can use a short ternary expression here:
a.map { |e| ( e == a.first ) ? e : e.to_f }
Another option (if you don't want to use ternary operators) is to do the following:
arr = arr.map { |e| (e == arr.first) && e || e.to_f}
This alternative is discussed here. A limitation with this method is that the first element in the array cannot be nil (or some other value that would evaluate false in a boolean evaluation), because if so, it will evaluate to the ||
expression and return e.to_f instead of just e.
Ruby 1.9 only?
arr = arr.map.with_index { |e, i| i.zero? ? e.to_s : e.to_f }
You can ask the objects themselves whether they're numbers.
"column heading".respond_to?(:to_int) # => false
3.1415926.respond_to?(:to_int) # => true
new_arr = arr.map do |string_or_float|
if string_or_float.respond_to?(:to_int)
string_or_float.to_int # Change from a float into an integer
else
string_or_float # Leave the string as-is
end
end
respond_to?(:to_int)
means "Can I call to_int
on you?"
to_int
is a method that only objects that are readily convertable to integers should have. Unlike to_i
, which is "I'm not very much like an integer, but you can try to convert me into a integer", to_int
means "I'm very much like an integer - convert me into an integer with full confidence!"
精彩评论