The Crystal Programming Language Forum

How to create a mapping of basic Types (Int32, String, Int8, etc) to their conversion methods?

For example: Int32's conversion method is to_i.
String is to_s, and so on.

# Please no code shaming (all this is just a contrived example)

test_string = "5000"

def extract_example(test_string, **t)
  pp t[:custom_key]
  case t[:custom_key]
  	when Int32
  		test_string = test_string.to_i
  		puts "I can't get this to call..."
	end
  test_string
end

pp extract_example(test_string, custom_key: Int32)

Please no macros (if possible)

Every number type has a .new method accepting a string, which in turn will invoke the respective String#to_x method.

2 Likes

https://play.crystal-lang.org/#/r/7bho

def example(string, **t)
  new_value = t[:selected_type].new(string)
  
  p! new_value
  p! typeof(new_value)
end

example("5000", selected_type: Int32)

AWESOME! Thanks @straight-shoota

Yeah I actually made use of that in Apatite. Very helpful.