get system cpu temperature in ruby

You can get the CPU temperature of your system by executing a command line program and capturing its output using Ruby. Here's an example code snippet:

main.rb
def cpu_temperature
  temp = `sensors | grep "Core 0"`.match(/(\+[\d\.]+)/)[1]
  temp.to_f.round(2)
end

puts "CPU Temperature: #{cpu_temperature}°C"
150 chars
7 lines

This code executes the sensors command, which is a utility for monitoring hardware sensors, to retrieve the CPU temperature. It then uses grep to filter the output for the temperature values, specifically for "Core 0". Finally, it uses a regular expression to extract the temperature value, rounds it to 2 decimal places, and returns it as a float.

Note that sensors may not be installed by default on your system. You may need to install lm-sensors or a similar package first, depending on your OS.

gistlibby LogSnag