Ruby 结构体 to_s()函数
to_s() 是Ruby中的一个内置方法,用于返回一个包含特定结构值的字符串。
语法 :struct_name.to_s()
参数 :该函数不接受任何参数。
返回值 :它返回结构的值。
示例 1 :
# Ruby program for to_s method in struct
# Include struct
animals = Struct.new(:name, :speciality , :found_in)
# initialize values
detail = animals.new("labrador", "bark" , "Newfoundland")
# to_s used
puts detail.to_s
输出:
struct name="labrador", speciality="bark", found_in="Newfoundland"
例2 :
# Ruby program for to_s method in struct
# Include struct
animals = Struct.new(:name)
#initialize values
detail = animals.new("golden retriever")
#to_s used
puts detail.to_s
输出:
struct name="golden retriever"