To convert a set of strings to a set of floats in Ruby, you can use the map method to convert each string into a float and then create a new set from the resulting array.
In this example,
string_set1
using the curly braces syntax, which contains the string values '1.1'
, '2.2'
, and '3.3'
.map
method on string_set1
to convert each string into a float using the to_f
method.to_set
method, resulting in a set of floats named float_set1
.puts
.require 'set'
string_set1 = ['1.1', '2.2', '3.3']
float_set1 = string_set1.map(&:to_f).to_set
puts float_set1
#<Set: {1.1, 2.2, 3.3}>
In this example,
string_set2
using the curly braces syntax, which contains the string values '4.4'
, 'hello'
, '5.5'
, '6.6'
, and 'world'
.map
method on string_set2
to convert each string into a float using the to_f
method.to_set
method, resulting in a set of floats named float_set2
.puts
.require 'set'
string_set2 = ['4.4', 'hello', '5.5', '6.6', 'world']
float_set2 = string_set2.map(&:to_f).to_set
puts float_set2
#<Set: {4.4, 0.0, 5.5, 6.6}>
In this tutorial, we learned How to Convert a Set of Strings to a Set of Floats in Ruby language with well detailed examples.