get system cpu temperature in celsius in ruby

You can use the sensors command, which is available in most modern Linux distributions, to get the system CPU temperature. You can execute the command using the backticks operator in Ruby and parse the output to extract the temperature value.

Here's a code snippet that demonstrates how to get the CPU temperature in Celsius:

main.rb
temp_output = `sensors | grep 'Core 0'` # Execute the sensors command and filter for the temperature of core 0
temp = temp_output.split(' ')[2]        # Extract the temperature value from the output
temp = temp.to_f                        # Convert the temperature value from string to float
puts "CPU temperature: #{temp} °C"     # Print the temperature in Celsius
366 chars
5 lines

Note that the sensors command might require administrative privileges to run, so make sure to run your Ruby script with the appropriate permissions, or add your user to the sudoers group.

gistlibby LogSnag